Get Images From Content of WordPress Post and display as Post Thumbnail

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 thumbnails but If you have not set an image as a featured image for a specific post then you will face some trouble in displaying post thumbnails with the post. 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.




2 thoughts on “Get Images From Content of WordPress Post and display as Post Thumbnail

  1. hi farooq, good tutorial , but if i want to display all the images in the post content, not only the first?

    thanks in advance

    1. Hi, code given in this tutorial is enough to display all images from any post, all you need to do is changing this line of code
      $first_img = $matches [1] [0];

      $matches is an array which contains all the images of a post, i have displayed the first image which is at $matches[1][0], for displaying all images you need to loop through this array of images.

Leave a Reply

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


502 Views