First image of WordPress post as featured if not set

By Faruque Ahamed Mollick

WordPress is the most popular CMS at this time. many bloggers are using WordPress for their blog. Also, WordPress is not only for a blog. You can extend its functionality using plugins that can work for a WordPress site.

You can see that in each WordPress post, you can add featured image. You have to add the below code in your theme’s functions.php file to support uploading featured image for WordPress posts:

add_theme_support( 'post-thumbnails' );

Now suppose, you don’t want to upload a featured image in your post and you wish the first image within your post content will be featured image automatically.

now in this tutorial, I am going to show you how to take the first image of your post content as featured image if you have not set the featured image or forget to set the featured image.

To get the first image of post content of each WordPress post add the below code inside your theme’s functions.php file:

// Get first image
function get_first_image() {
  global $post, $posts;
  $first_image = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_image = $matches [1] [0];

  if(empty($first_image)){ //Defines a default image
   // Set the default image if there are no image available inside post content
    $first_image = "/img/default.jpg";
  }
  return $first_image;
}
// End Get First Image

After that, you have to place <?php echo get_first_image(); ?> in that place of WordPress post loop of the template file where you want the first image of the post to be displayed.

Now suppose you want to show the first image of the post content when there are no featured image is set. So below is the code which can do this task:



<?php
// This code must should be inside WordPress post loop
if ( has_post_thumbnail() ) {
    the_post_thumbnail();
}
else {
    echo get_first_image();
}
?>

After you place it inside your template file, you will able to see the first image of your post as featured image if the featured image is not set.

 

Leave a Reply

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