Automatically Set the First Post Image as a Featured Image in WordPress

Have you ever run into the situation where you have a lot of posts without a featured image and you need to change that to be able to use WordPress Themes which depend upon featured images in their layout? We’ve got a simple solution to this problem.

WordPress functions php file

Everyone likes to change up their WordPress site every once in a while, whether its by adding new plugins to expand the functionality, or getting a brand-new look with a fresh theme. Such changes don’t always go smoothly though; implementing a new plugin or theme can bring its own set of issues; for example, what if you make the jump to a new theme, but its layout relies upon featured images from posts to deliver its content while your previous theme did not? You could be left with hundreds of posts that don’t have a featured image assigned, which leaves you with the frustrating task of going through each post one-by-one and assigning a Featured Image via the Edit Post screen, wasting several hours in the process.

So what can you do if you’ve got a lot of posts without a featured image, and you need to change that ASAP so you can use your new featured-image-based theme? If you have a thing for tedium then you could of course do things manually, but we’ve got a much simpler solution that will take a lot of the sting out of this task.

The Featured Image generator function

The script below will be able to take care of your image problem, and all you’ll need to do is copy the code and add it into your theme’s functions.php file:

function auto_featured_image() {
    global $post;

    if (!has_post_thumbnail($post->ID)) {
        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
        
	  if ($attached_image) {
              foreach ($attached_image as $attachment_id => $attachment) {
                   set_post_thumbnail($post->ID, $attachment_id);
              }
         }
    }
}
// Use it temporary to generate all featured images
add_action('the_post', 'auto_featured_image');
// Used for new posts
add_action('save_post', 'auto_featured_image');
add_action('draft_to_publish', 'auto_featured_image');
add_action('new_to_publish', 'auto_featured_image');
add_action('pending_to_publish', 'auto_featured_image');
add_action('future_to_publish', 'auto_featured_image');

Inserting the function into your theme

Don’t worry if you’re not familiar with adding scripts to your WordPress theme’s files as it’s a very simple process. There are two main options for adding the script to the functions.php file; first, you can use FTP to connect to your server, download the functions file, make your changes and then reupload the file, replacing the original, or you can utilize the editor that is built into WordPress to access and change the file directly in the WordPress dashboard.

Using FTP

The FTP method might seem long-winded, but if you’re familiar with the concept and how to use it then it’s actually an extremely fast and accurate solution. If you’re not sure where to start with FTP, you can our Beginner’s Guide to FTP blog article to get the lowdown on what it does and how. Once you’re ready to go, then just follow these basic steps:

  1. Connect to your server via FTP and navigate to your current theme’s folder, which you’ll find in wp-content → themes in your WordPress installation. Make sure to open the correct folder for your theme, as every theme has its own functions.php file and adding the script to the wrong, inactive theme won’t do you any favours!
  2. Download the existing functions.php file from the theme folder, and open it in the code/text editor of your choice (we like to use the Sublime Text code editor, but whatever you’re comfortable with will do).
  3. Copy the entire code provided above and paste it at the end of the functions.php file’s code. Save the changes.
  4. With the file now modified accordingly, connect to your server via FTP once again and upload the updated file to the theme folder, replacing the original. You’re now ready to go!

Using the WordPress Editor

The WordPress Editor allows an admin to modify the core theme files in the dashboard without the need for FTP access; an elegant solution if you’re not comfortable with FTP and just need a quick solution. Making the changes with this method is very easy:

  1. In the WordPress Dashboard, click on Appearance → Editor in the left menu to open the editor screen.
  2. You’ll now be on the Edit Themes page for your current active theme; a list of theme files is on the right, and the code to be modified will appear in the main editor window. Under the Templates heading of the theme file list, look for the functions.php file and click on it to open it in the editor.
  3. You can now see the code of the functions.php file in the main window of the editor; scroll down to the end of the file and then copy and paste the script above at the end of the existing code.
  4. Now click on the Update File button under the editor to save changes; the code is now ready!

How the script works

So you’ve added the script to your functions file; now what is it actually going to do? It’s really very simple; whenever a post is viewed or a new post saved, the script checks the specific post to see if it has a featured image set. If not, then the script checks for others images in the post, grabs the first one it find, and sets this image as the featured image.

Something to be aware of here is that this instruction will be executed every time a post is displayed, which can have a slight performance hit on your website. For this reason, we recommend removing the following lines of code from the function once all of the featured images have been generated for existing articles:

// Use it temporary to generate all featured images
add_action('the_post', 'auto_featured_image'); 

There are two other important takeaways from this:

The featured image must be removed from the media manager, and each image may only be automatically added as a featured image once. That means if you’ve already used a particular image as a featured image in a post, any future posts that use the same image will not be able to automatically use it as the featured image. For this reason we recommend using this solution only to migrate your older posts across to the updated format; once this is done and all earlier articles have been updated, the featured image can be manually set for any new posts as this method allows for duplicates if needed.

Automatically Set the First Post Image as a Featured Image in WordPress 4.425 (88.33%) 36 votes
Share
This article was first published September 12th, 2016
  • Richard Bean

    This doesn’t seem to work with the latest version of wordpress… do you have an updated version of the script?

  • Christopher Ziyo

    Not work in WP 4.7.2.

    I add code above to the functions.php of my theme, and after entering into post which do not have featured image nothing is change. Still this post dont have attached a future image after reloading page with posts list

    Is this works only in Gavick Themes?

    • Thiện Nguyễn

      Hi Chris, try my code :)

      //function get media id
      function pippin_get_image_id($image_url) {
      global $wpdb;
      $attachment = $wpdb->get_col($wpdb->prepare(“SELECT ID FROM $wpdb->posts WHERE guid=’%s’;”, $image_url ));
      return $attachment[0];
      }

      //select all posts
      $wpb_all_query = new WP_Query(array(‘post_type’=>’post’, ‘post_status’=>’publish’, ‘posts_per_page’=>-1));
      // regex select img src
      $regex = ‘/src=”([^”]*)”/’;

      if ( $wpb_all_query->have_posts() ) :
      //Start loop
      while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post();
      //get post content
      $content = get_the_content();
      //get post ID
      $current_post_id = get_the_ID();

      //get images in content
      preg_match_all( $regex, $content, $matches );
      $post_image_url = array_reverse($matches);

      /*get media_id of 1st image*/
      $image_id = pippin_get_image_id($post_image_url[0]);

      /* check media existed and post thumbnail*/
      if($image_id && !has_post_thumbnail())
      {
      update_post_meta( $current_post_id, ‘_thumbnail_id’, $image_id );
      }
      //set default image if there is no image in content
      elseif(!has_post_thumbnail()){
      //replace ‘25011’ with your default image’s id
      update_post_meta( $current_post_id, ‘_thumbnail_id’, 25011 );
      }
      endwhile;//end loop
      //reset post data
      wp_reset_postdata();
      endif;

    • Thiện Nguyễn

      Copy the code below into the end of your theme’s functions.php, reload your website and enjoy. Please remove this code when everything’s done.

      //function get media id
      function pippin_get_image_id($image_url) {
      global $wpdb;
      $attachment = $wpdb->get_col($wpdb->prepare(“SELECT ID FROM $wpdb->posts WHERE guid=’%s’;”, $image_url ));
      return $attachment[0];
      }

      //select all posts
      $wpb_all_query = new WP_Query(array(‘post_type’=>’post’, ‘post_status’=>’publish’, ‘posts_per_page’=>-1));
      // regex select img src
      $regex = ‘/src=”([^”]*)”/’;

      if ( $wpb_all_query->have_posts() ) :
      //Start loop
      while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post();
      //get post content
      $content = get_the_content();
      //get post ID
      $current_post_id = get_the_ID();

      //get images in content
      preg_match_all( $regex, $content, $matches );
      $post_image_url = array_reverse($matches);

      /*get media_id of 1st image*/
      $image_id = pippin_get_image_id($post_image_url[0]);

      /* check media existed and post thumbnail*/
      if($image_id && !has_post_thumbnail())
      {
      update_post_meta( $current_post_id, ‘_thumbnail_id’, $image_id );
      }
      //set default image if there is no image in content
      elseif(!has_post_thumbnail()){
      //replace ‘25011’ with your default image’s id
      update_post_meta( $current_post_id, ‘_thumbnail_id’, 25011 );
      }
      endwhile;//end loop
      //reset post data
      wp_reset_postdata();
      endif;

  • Stefan

    Great! Exactly what I am looking for.

    BUT: I use WPML for the management of 2 languages. So every post is available in German and English – with the same featured image of course.

    As far as I understood, that won’t work. Will it?

    Thank you for a hint
    Stefan

  • Nice post and it’s working on WordPress theme
    Thank you

  • Great post, it’s working on my website
    Thank you for sharing with codes

  • kang baha

    NIce post, it work on my wordpress 7.2.0, thank’s a lot

  • Nishe

    Unfortunately does not work with WordPress 4.7 :(

  • thank you! worked like a charm.

  • Thank you for sharing the codes

  • Pmizzle.

    Boom. Thank you.

  • Jason Craig

    This is not working currently. Latest WordPress is being used.

  • EDWIGE

    Thanks a lot It works!!!
    But my images are big and above the title.
    How can I put the featured image on the left and reduce the size?

  • RS Pandey

    Sorry it did not work for me. I’m using WP 4.6.1 theme. What could be the reason ?

  • thanks

  • mauril0pES

    Hello, this is not working for me anymore. A while ago, I used it on one of my sites and it worked, now I did it on a new site and it does not work. My new site has WP 4.6.1. Any help would be appreciated.

  • Thanks , You saved my day.

  • Larry Levenson

    I echo the others — perfect!!!! 500 blog posts got featured image marked in a couple minutes. :) THANK YOU!

  • RintKid

    Thanks !

  • Ian

    This doesn’t work for me at all using Yeah! Theme’s Elegance theme. There are post type options like: standard, video, gallery, etc. Does that make a difference? Thanks

  • James Brako-McComb

    This is absolutely amazing! Thank you so much!

  • Thanks for this code !! works perfect !!

  • I have post_type=portfolio How to use for that?

  • Hi there. Thanks for the codes. :)

  • Hello,

    Rather than automating Featured Images is there a way to add them by using Custom Field?

    • Yes, you have to just iterate through the custom fields instead of the attachments for the post.

  • Doesn’t seem to work for the already created posts. Worked though for the ones to be published after the insertion of the function. I’m testing it with WP4.0. Any chance i’m missing something?

    • Dziudek

      Hello,

      Code:

      // Use it temporary to generate all featured images
      add_action(‘the_post’, ‘auto_featured_image’);

      Is used to generate images from posts – but of course these posts must be displayed at least once time to generate post featured image.

      • You mean actually visit the post in the front-end? If yes, it won’t help in my case as posts are rss generated and link directly to their original sites.

        • Dziudek

          Sorry, there is no other solution.

      • Мая Иванова

        not working with WordPress 4.7 :(

  • Sharon

    How do you NOT set the featured image on pages – I tried

    if (!has_post_thumbnail($post->ID)&post_type=post) {
    but it didn’t work. I only want to set the featured image on blog posts not pages.
    Appreciate any help anyone can give
    Sharon

    • Dziudek

      Your condition is wrong – you should use && instead of & and == ‘post’ instead of =post

      • Sharon

        Thanks, that didn’t work for me? However I have found a solution to turn off featured image using a theme option for a page template. Thanks again

  • The save_post hook should be enough for new posts.
    And the post ID can be retrieved with the parameter passed by the save_post action itself.

  • Conny Svitzer

    It seems like its adding the featured image like it should but missing the wp_update_post or am i missing something?