First image of WordPress post as featured if not set

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 = '';
  $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:

// This code must should be inside WordPress post loop
if ( has_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.


One response to “First image of WordPress post as featured if not set”

  1. Jose says:

    Hello, I am trying to put the codes in my theme. But I am not successful.
    I use the “Ribbon lite” theme
    Please, where should I put the codes. In theme files.
    Sorry for the inconvenience.
    I hope you can help me.
    Best regards.

Leave a Reply

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