Display or Retrieve Images From WordPress Post Content Even If They are not Featured Images

display any image from the post content

How to Get Any Image from WordPress Post Content :

WordPress has a number of functions related to displaying images and post thumbs but If you have not set an image as a featured image for a specific post then you will not find any function for getting and displaying an image which is already uploaded in the post content. I am writing this short tutorial because I have faced this similar problem when I first started developing with WordPress.

The solution I am going to present here is based on regex, don’t  worry you do not have to be good at using regex because I am going to share complete code, required for displaying or getting the first image from your post content. This tutorial is just for showing you the way, how to get any image from WordPress post content, now which image to retrieve or where to use that image is completely up to you.

// display first image of a post

function first_image_of_postContent() {

global $post, $posts;

$first_img = ''; // this variable will hold first image of our postContent.

$imgString;

ob_start();

ob_end_clean();

$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

// assigning first image to our variable”$first_img” from the array of all images our post contains.

$first_img = $matches [1] [0];

if(empty($first_img)){  //Defines a default image

$first_img = content_url()."/uploads/default.jpg";

}

$imgString ="<a href='".get_the_permalink()."' class='thumbnail-wrapper'><img src='".$first_img."' alt='' class='post-excerpt-image'/></a>";

// I have returned the image within a hyperlink , if you want get just the image then remove the “<a></a>” tags.

return $imgString;

}

// end of getting first image of wordpress post

 

Copy and paste the above code in your theme “functions.php” file and call “first_image_of_postContent()” function in any theme template where you want to get or display this image. 

Note: The above code is tested in theme’s functions.php file and is working, it will work in plugin but I personally have not tested this in plugins.

If you do have any problem related to this tutorial, please do ask in comments, I will be glad to help you.




Leave a Reply

Your email address will not be published. Required fields are marked *


174 Views