WordPress Excerpt Showing First image of Post as Thumbnail if exists

In my own site I wanted a thumbnail to be shown in the excerpt with the thumbnail images being picked up from the first image of the post.It was also desired that no default image should be shown when the post does not have an image.So here we are avoiding a default image display.

to the functions.php in the theme folder add this code

function get_post_img() {
  global $post, $posts;
  $first_img = '';
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  //if(empty($first_img)){ //Defines a default image
    //$first_img = "/images/default.jpg";
  if (!empty($first_img))
		//return $first_img;
		$hmc.="<a href=\"".get_permalink()."\"><img style=\"float:left ; list-style:none;\" src=\"".$first_img."\" height=\"60px\" width=\"60px\"></a>" ;
		return $hmc;

Now we simply need to call the function in our theme template.I am assuming that the theme’s template files index.php,archive.php.and search.php are calling the_excerpt() instead of the_content() if not,first you should open these files and remove the the_content() function and replace it with the_excerpt().This will show an excerpt when categories are browsed,homepage is opened and search results are displayed.

just before the_excerpt(); add the code

<?php echo get_post_img() ;

This will display the post thumbnail in the excerpt if the image has a post else not.

That is all.

If you liked this article please do leave a reply and share it with friends.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.