Get The First Image Of WordPress Post As Featured Image

Hello, I am here again with a new WordPres solution for WordPress developers and I hope this tutorial is also going to be helpful for you.

Sometimes WordPress users may forget to post a featured image. In that case, it will really work if the first image from the content from that WordPress post is automatically set as the featured or thumbnail image. Also, it can save time by avoiding choose separate image as featured image.

Below is the code snippet:

// make the first image of WordPress post as featured image
function first_image_as_featured() {
global $post, $posts;
$first_img_featured = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img_featured = $matches [1] [0];
if(empty($first_img_featured)){ //Defines a default image
$first_img_featured = "/images/default.jpg";
}
return $first_img_featured;
}

Put the above code in your theme’s functions.php file. You can also put above codes by creating your own plugin.

Now use the below code in your WordPress post loop:

<?php
 if (has_post_thumbnail()) { ?>
        <?php the_post_thumbnail(); ?>
  <?php } 
        else { ?>
        <img src="<?php echo first_image_as_featured(); ?>" />
        <?php
 } 
?>

That’s all you need to do. Now you will able to see the first image of your post as featured image if you don’t set any featured image at the time of writing the post.

Follow all the steps that I have mentioned in this article and test it. Was that not so easy? You can use this process in your own WordPress theme to enable the feature if featured image is not set then use the first image from the post as featured image.



One response to “Get The First Image Of WordPress Post As Featured Image”

  1. Gayan says:

    Hello , actually i have try this code and it worked well .. but there is one more issue . the code always taking 2nd image inside of post ? any idea ?

Leave a Reply

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