Automatically Set the Featured Image in WordPress

Often I find myself forgetting to click on “featured image” when I’m writing a post. But I know I need one because it makes the world go ’round for WP Force.

What’s the solution? Automatically set the featured image.

Here’s a quick snippet of code you can throw into your functions.php file that will your theme automatically set it to the first available image. Note, you can always go and set another image as the featured image if you want to. It checks to see if a featured image exists and if it doesn’t, picks the first one.

UPDATED – 02/19/12 After a few reports of this function not working under 3.3.1, I made some tweaks to it so it uses the native set_post_thumbnail() function, as well as adding a few actions at the end to ensure the featured image gets set properly. Id you see anything not working right, please let me know in the comments.

function autoset_featured() {
          global $post;
          $already_has_thumb = has_post_thumbnail($post->ID);
              if (!$already_has_thumb)  {
              $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);
                                }
                           }
                        }
      }  //end function
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

Tagged:

Comments

  1. dhruv bhagat says:

    i cant set featured image in wordpress 3.3 ??? :(
    please HELP !!

    • Jon says:

      Are you not able to see the “set featured image” setting when uploading the image?

      Did you safe the post already? Because if you’re using the code above and you save the post, it will automatically get set and you won’t need to set it manually.

  2. Fabrizio says:

    Incredible Tips! Is it possible mod your script and add a custom field to autosave in _thumbnail_id field?
    Thank you

    • Jon says:

      It actually already does that. However, any field that begins with an underscore, is hidden from the UI.

      You could certainly add a second line to that add_post_meta and have it save to a second field that doesn’t begin with an underscore, if you want it to be a viewable custom field.

      Here are the docs on custom fields starting with an underscore – Codex

  3. ghantoos says:

    Thanks for sharing this tip!

    • Hi, I copied the code above and placed it in the functions.php file. Now when I post from the WP ios app the code works and sets the first image in the post as the featured image. However, when I post using the WP web interface it will not set the featured image and that space remains blank. Why does the ios app work and not when posting from the pc browser?
      Thanks.

      • Jonathan Dingman says:

        That’s really strange. I never tested this with the iOS apps, I’ve only tested it from the browser.

        Did you try saving the draft and see if it gets set before publishing?

        • Thanks for responding. I did save the draft also but it won’t work. I even tried posting the draft from the iOS app but no featured image. It’s as if the code does not execute in the browser and only works when the wp iOS app is used for direct posting. I am going to change the theme and test it in the new function.php
          Regards.

          Ok. After various experiments and almost pulling out the rest of my hair, I figured out that if I insert an image using the media library insertion tool (like insert an image into the post … and this is what the ios app does too apparently), your code works well. It wont work if I drag and drop a pic into the post being edited on the WP browser editor.
          Regards.

          • Jonathan Dingman says:

            I updated the code to work properly in 3.3.1, please give it another shot and see if it’s working for you now.

  4. Shivaji says:

    This code does nothing in latest WP 3.3.1.

    • Jonathan Dingman says:

      Weird, I wonder why it’s not working for you.

      I use this code on this site, and we’re running 3.3.1. Works without any issues for me.

  5. Shivaji says:

    Though the code looks promising but the instruction to add those code may not be clear to me. What I did is, added that code snippets into themes functions.php file. Then I edit one post and Click on UPDATE and it does nothing. The “Set featured image” is set to no image.

    • Jonathan Dingman says:

      That is the correct method to integrate this function.

      And you have an image uploaded and attached to the post already?

      • Shivaji says:

        I have total of 250 articles and every articles got 4 to 5 images embedded into the post itlself. Anyway, here goes my site demo (dot) jeddahbeautyblog (dot) com. you see in the home page, the thumbnail boxes are blank and that I wanted to fill-up using your code. I can also give you access to site admin if I have your email id.

  6. Farhan says:

    can you guide me where to post this code in function.php???

  7. HART says:

    Hello! I was wondering if you can offer your viewpoint. I’ve installed a theme that is drip feeding posts and there is a custom field NOT called “thumb” or “thumbnail” or anything conventional … but, I would like to somehow be able to set the featured image of each post to BE that specific custom field image automatically. It looks like your code in the functions file is the way to go, but I can’t seem to figure out how.

    Do you think that’s possible?
    Thanks!
    HART

    • Jonathan Dingman says:

      Hi HART,

      The code below is under the assumption that your custom field *is* the URL to the image you want featured. I haven’t tested this, but it should give you a pretty good direction.

      $oldField = get_post_meta($post->ID, ‘your_custom_field’, true);
      if ( !empty ( $oldField ) ) { set_post_thumbnail($post->ID, $oldField); }

      Then you will need to figure out which hook works for your theme and “drip feeding” to ensure that it gets set at the correct time.

      • HART says:

        thanks! That looks promising, where I would change “your_custom_field” to the default in my drip field … but, where would you add this code to in relation to the code above? I wish I could “get it” but, instead all I’m getting is the dreaded white screen when I add it.
        HART

        • Jonathan Dingman says:

          Ooops, I missed a ) in the above code. I corrected it.

          I wouldn’t use these two functions in combination with each other, they should be used separately.

          You’ll need a bit of programming experience to achieve what you want to do, so I’d suggest hiring a WordPress developer to get the job done.

          • HART says:

            That code actually worked with the extra bracket :D and set the featured post correctly to the custom field I selected!! Muchly appreciated!

            Although my problems aren’t completely solved, it definitely shows that my theme has an issue displaying the featured image in a multisite environment. At least now I can prove it by pointing to where the featured image is not, whereas before it was more like ‘say wut?’ lol

            Thanks again Jonathan / HART

  8. Hmmm not working for me at archiseek.com – not overriding the default for no thumbnail.

    • Jonathan Dingman says:

      Hi Paul,

      Is there already a thumbnail set? Because if there is, it won’t change it. This code only checks to see if there isn’t a thumbnail set, then goes ahead and grabs the first image and sets that as the featured image.

      Please clarify on the conditions for your posts.

  9. Mo says:

    Hi Jon,

    Thank you for that great code. I am looking for something very similar. Maybe you can help me to figure it out. I am using a custom field to hold the youtube id of my posts. The theme automatically renders a preview image [ src="http://mydomain.com/wp-content/uploads/-185x135.jpg">] on the blog page and the video on the home page. Now I would like to set the preview image automatically as the featured image. Can you point me in the right direction or can I hire you to make your script work for me ?

    Thank you for your great work
    m.

  10. Chetan Singh says:

    I really like the code here because it only requires one set of code to be inserted in one place as against adding 2-3 different long codes in different areas. However at this point the codes are not working for me at all. Is there any thing I am missing. I am adding it at the very bottom of my functions.php file before ?>

    I would really appreciate your help as I liked the code alot.

    • Jonathan Dingman says:

      Yes, add it before the ?> at the bottom of the file.

      Can you be more descriptive in what is not working for you?

      Please make sure you’ve uploaded an image to the post already.

      • Chetan Singh says:

        Thanx for the quick reply Jon.
        Well FYI, I am using a auto posting plugin called WP-Robot and all my post gets added automatically along with the image. I have checked it myself when I clicked on the on article link on my homepage the post page has an image.

        I inserted the given code in functions.php folder just before ?>
        However when I access my website I cannot see any changes.

        Thanks & Regards
        Chetan Singh

        • Jonathan Dingman says:

          It doesn’t surprise me that it’s not working then, as the code above is designed to hook into manual publishing and updates of a post, rather than an automated system.

          You would need to modify the code to hook into WP-Robot. I recommend speaking to the author of that plugin.

          • Chetan Singh says:

            Thanks alot Jon for your help and quick reply. I appreciate your efforts. God Bless You.

  11. Quang says:

    Thanks Jonathan. It works perfectly.

  12. Pascal says:

    Hi, I’m using genesis framework and copy your codes to the functions.php but it gives me a server error 500. I’m running WP 3.3.1 Any idea why?
    Thanks

    • Jonathan Dingman says:

      I would make sure you don’t have any trailing spaces at the end of the file, also make sure that you aren’t adding another

  13. Elitista says:

    Hi, first of all thanks for the trick.
    I am using the WPeMatico plugin to autopost. The post get the image auto featured but my theme dosent show it.
    Can i hire you for do the job?

    Thanks

    • Jonathan Dingman says:

      First thing I would check would be to see if your theme is using featured images at all to begin with. If they aren’t, then you would need to add support for it.

      Also, see the above comment about it not being designed to work for “auto-blogging” content. It’s only designed for manual posting.

  14. Miroslav says:

    Hello your code is working very good :) Thank you for that! My question is: Is there way that code will also add feature image also from external source? Most of my images are not stored on my server.
    Thank you

    • Jonathan Dingman says:

      Unfortunately, WordPress does not allow for “external” images to be set as the featured image. The image must be saved to local storage on the server.

      I have some code I’ll be releasing soon, which handles this gracefully.

  15. Matt says:

    Jon – thanks for posting this great info. I’ve implemented your code into our functions.php file and it’s working great, however we do have a few posts that automatically post via RSS feed and all the images in these posts are linked by URL. Is there any code that I can add that will pull those linked images and make them featured as well?

    • Jonathan Dingman says:

      No problem, happy to help.

      As per my response above to Miroslav, you’ll see I’m prepping some code to be released. I’ll be happy to e-mail you both the code before I’ve released it.

      Cheers

  16. Jonathan says:

    I can’t get this to work? I added it to the functions.php and ALL my posts dissappeared!! Granted I’m limited to using wordpress 3.0. Could that be why? Do you have an older version?

    • Jonathan Dingman says:

      Hi Jonathan,

      The code above doesn’t have any capability of deleting every post, so I would have to imagine it was something else in your theme and/or plugins.

      Post Thumbnails were introduced in WordPress 2.9, but while I haven’t tested the code on WordPress 3.0, I imagine it should still work. Sorry, no previous versions of the code is available.

  17. Bharat Chowdary says:

    This is really helpful code, thanks jonathan….

  18. Pete says:

    It doesn’t appear to be working for me. That is, there is no thumbnail picture visible in the featured image box in the post edit page.

    • Jonathan Dingman says:

      You need to make sure your theme has support for Featured Images, otherwise this will not work.

      • Pete says:

        Thanks it works now… you might like to mention this in your post too…

        // Turn on featured images
        add_theme_support( ‘post-thumbnails’ );

  19. Dave says:

    Hi Jonathan,

    First, will your code work in WP Ver 3.3? Second, I curate content with stand alone PC software (not autoblogging) that posts to my blog when finished. However the software doesn’t have the capability to set a featured image (trying to coax the developer on the prospects of adding it as a feature – if possible) and I have to log into WP and manually set the image. The content I post does have images. Will your code work for this?

    • Jonathan Dingman says:

      Hi Dave,

      This code is tested on WordPress 3.3.1, so yes it should work.

      If you’re using a third-party application to post blogs, it probably will not work. I have not tested the code at all, using third-party applications.

      You would need to write the post, then go in and click “save” to each post — probably. I don’t know for a fact, because I haven’t tested it.

      I would just test out the code on your site using your software, that’s the best way to know for sure or not.

  20. matthew says:

    Is there a way to make it work with the second available image in a post and not the first?

    • Jonathan Dingman says:

      Hey Matthew,

      Certainly, you would want to use array_shift() to do that. There are examples on the WordPress forums here.

      You would need to make sure you get 2 images, instead of just 1, by changing it to:

      $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=2" );

      numberposts=2

      Then you would need to use array_shift and do something like this:

      if ($attached_image) {
               $attached_image = array_shift($attached_image);
               foreach ($attached_image as $attachment_id => $attachment) {
               set_post_thumbnail($post->ID, $attachment_id);
               }
      }

      I haven’t tested, but something using array_shift should work.

  21. So helpful!!!! You just saved hours of my life.

    Thanks

  22. John says:

    You know what would be really helpful? Make this a plugin. I’d pay you for it.

    • Pete says:

      There’s already a plugin that does this. This way I like as i can save it in my functions.php and not bother to have to install it every time I make a website.

  23. cestbibi says:

    Thank you for this very useful contribution. I’d like to let you know that this doesn’t seem to be working anymore with 3.4-beta, maybe you can have a look . Thanks again!

    • Jonathan Dingman says:

      I’m going to hold off until it’s at least an RC before doing any testing. Thanks for the heads up though.

Trackbacks

  1. [...] Another way to set featured image for all posts, without using any plugin is to use the function by Wpforce. You can add this function to your theme and it will set the featured image. More details available here. [...]

  2. [...] 代码来自:Automatically Set the Featured Image in WordPress [...]

  3. [...] Hat tip to WP Force. Related PostsWordPress Gravity Forms Plugin Review Part 2In part 2 of the Gravity Forms plugin review we're going to go over some of the advanced features an…Featured PSD Template Seller: WebvillaTotal Bounty™ is proud to feature the work of our newest seller Webvilla. From Cracow, Poland…Featured thumbnail goneI've installed a new mystique 3.0 & the thumbnails that usually appear at the top left of posts …Featured Stock Photo Seller: SkybitsMarch Uploads Get 60 Percent CommissionsShare this:ShareDiggFacebookEmailPrintStumbleUponReddit Tags: code snippets, WordPress [...]

What are your thoughts?

*

Read previous post:
Online Security
Dre Armeda on End-User Security

Good friend and power-hacker/user/designer/developer, Dre Armeda, speaks on end-user security at WordCamp Chicago 2011. Dre is co-founder of Sucuri and...

Close