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.

UPDATED – 07/15/12 Pete, in the comments, asked about how to set a default image if there were no images present in the post. I’ve added a second chunk of code beneath the original code with the example of how to do it.

function wpforce_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', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

Set a Default Featured Image

If you do not have an image in the post, the following code will let you set a default image to be set as the featured image. The only change from above is the else {} statement that sets a default.

NOTE: You must edit the attachment ID according to your WordPress site. The example below uses the attachment ID “414” — you must use your own.

function wpforce_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);
                                }
                           } else {
                                set_post_thumbnail($post->ID, '414');
                           }
                        }
      }  //end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

Comments

  1. By dhruv bhagat on

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

    Reply »

    • By Jon on

      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.

      Reply »

  2. By Fabrizio on

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

    Reply »

    • By Jon on

      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

      Reply »

    • By on

      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.

      Reply »

      • By Jonathan Dingman on

        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?

        Reply »

        • By on

          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.

          Reply »

          • By Jonathan Dingman on

            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.

    • By Jonathan Dingman on

      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.

      Reply »

  3. By Shivaji on

    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.

    Reply »

    • By Jonathan Dingman on

      That is the correct method to integrate this function.

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

      Reply »

      • By Shivaji on

        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.

        Reply »

        • By Jonathan Dingman on

          I updated the code to use the native WordPress function of “set featured image”.

          I also cleaned up some of the code to ensure it uses

          $post->ID

          properly.

          Reply »

          • By Shivaji on

            Yes, this time it work. Featured Image automatically taken from post images. Thank you !

      • By on

        when i put this code anywhere in functions.php the main index page goes blank???
        Plz Help!!!!

        Reply »

        • By Jonathan Dingman on

          First and foremost, make sure your functions.php file begins with: <?php

          If you’re still having issues, read through Theme Development on the Codex.

          Reply »

  4. By on

    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

    Reply »

    • By Jonathan Dingman on

      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.

      Reply »

      • By on

        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

        Reply »

        • By Jonathan Dingman on

          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.

          Reply »

          • By on

            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

    • By Jonathan Dingman on

      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.

      Reply »

  5. By Mo on

    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.

    Reply »

    • By Jonathan Dingman on

      We should be able to whip something up. Let’s talk via email.

      Reply »

  6. By Chetan Singh on

    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.

    Reply »

    • By Jonathan Dingman on

      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.

      Reply »

      • By Chetan Singh on

        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

        Reply »

        • By Jonathan Dingman on

          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.

          Reply »

          • By Chetan Singh on

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

        • By on

          hi chetan i’m also using wp robot on my site and i have the same issue , i want the post image set as featured image , please let me know if u got any solution for that yet , thak you.

          Reply »

  7. By Pascal on

    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

    Reply »

    • By Jonathan Dingman on

      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

      Reply »

  8. By Elitista on

    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

    Reply »

    • By Jonathan Dingman on

      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.

      Reply »

  9. By on

    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

    Reply »

    • By Jonathan Dingman on

      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.

      Reply »

      • By Mel on

        great code! :) I cant wait for this new code to come out too! thank you jon!

        Reply »

      • By dashou on

        Any update for your new code to support extral image?
        Many thanks for your great codes!

        Reply »

        • By Jonathan Dingman on

          WordPress does not support the use of external images as a featured image, so this will unfortunately never be possible. You would need to build code that downloads any external image and saves it to the post, then sets it as the featured image. Doing that for *every* external image could be heavy for a site, so I wouldn’t recommend doing it.

          Reply »

          • By Pete on

            “dashou commented on Automatically Set the Featured Image in WordPress.
            Any update for your new code to support extral image? Many thanks for your great codes!”

            Justin Tadlock’s “Get the image” plugin does this.

  10. By on

    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?

    Reply »

    • By Jonathan Dingman on

      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

      Reply »

  11. By on

    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?

    Reply »

    • By Jonathan Dingman on

      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.

      Reply »

  12. By Pete on

    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.

    Reply »

    • By Jonathan Dingman on

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

      Reply »

      • By Pete on

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

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

        Reply »

        • By Jonathan Dingman on

          Good idea, Pete, thanks. I’ll get that into the code above soon. Cheers

          Reply »

  13. By Dave on

    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?

    Reply »

    • By Jonathan Dingman on

      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.

      Reply »

  14. By on

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

    Reply »

    • By Jonathan Dingman on

      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.

      Reply »

  15. By on

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

    Reply »

    • By Pete on

      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.

      Reply »

  16. By on

    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!

    Reply »

    • By Jonathan Dingman on

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

      Reply »

  17. By Kolo on

    Hi, sorry if this question is obvious or has already been answered. Will this code work with already published posts that don’t have a featured image set, or does it only work going forward with new posts?

    Thanks!

    Reply »

    • By Jonathan Dingman on

      Hi Kolo,

      This code is designed to work only when publishing a new post. It will not work retro-actively for older posts.

      Reply »

  18. By on

    Jonathan,

    Great code! I too have posted posted via an automatic poster via RSS. I saw you mentioned you had some code you’d be releasing soon that would work with external images. Has this code been released yet? If so where? Thanks so much for the above code!

    Reply »

    • By Jonathan Dingman on

      Hey Eric,

      Actually, the code I have is for automatically getting an external thumbnail, then setting that as the featured image. I don’t have any plans to develop code for setting the featured image for auto-posting via RSS.

      Reply »

  19. By Fabrizio on

    Excellent snipett Jonathan.
    If I remember correctly, your script grabs the first image attached to the post. Is it possible to modify the snippet to automatically save the first image of the post inserted in post with this tag: ?
    You solve me a lot of problems! Thx

    Reply »

    • By Jonathan Dingman on

      Hi Fabrizio,

      I’m not quite sure what you’re asking. Can you pastebin.com an example and maybe I can figure it out?

      Thanks

      Reply »

  20. By Fabrizio on

    You’re right Jonathan I’m sorry. Pratically I almost wonder if you can learn me how to insert, as Featured Image, an image loaded from a server outside its own domain: here code: http://pastebin.com/iYTGXQMt
    Thx a lot

    Fabrizio

    Reply »

    • By Jonathan Dingman on

      WordPress actually doesn’t allow you to set external images as the featured image, it has to be a locally-saved image.

      The code in this plugin may help with what you’re looking for.

      Reply »

  21. By Fabrizio on

    Jonathan, while I await your reply, I read again all the comments and I have implemented the snippet as you suggested to HART on 21, feb. We’re almost there! Here code: http://pastebin.com/0JrwHQ8q
    In fact I was able to automatically insert the url of a custom field as a Featured Image. The last step is to do everything with a url in an image to an external server. How can the code be implemented to this effect?
    Thanks again!

    Reply »

    • By Jonathan Dingman on

      That code to HART was untested, so I can’t confirm if it works or not.

      But again, as noted in the above comment, you can’t use an external image as the featured image.

      Reply »

  22. By Sean on

    Hello – this looks fantastic. I was wondering – do you know of a way to remove the embedded image from the post automatically once it’s been added as the featured image? I’m hoping to use it so I can post from the iOS app, and my site uses featured images everywhere – so as it stands in my loop it’s displaying the image twice, once where the featured image is called and again in the post content.

    Hope the question makes sense!

    Reply »

    • By Jonathan Dingman on

      Hi Sean,

      That would be pretty tricky to do via code.

      You should be able to do it via iOS though. Upload the image, save the draft (which sets the featured image), then remove it from the post content.

      Reply »

  23. By Pete on

    Will the featured image change if I re-arrange the order of my images? If it won’t can this be done? That is, the featured image is the first image “by order” OR if no order has been set then the first image uploaded… clear as mud? :)

    Reply »

  24. By on

    Using this on WordPress 3.4 and Thesis 1.8.5. Works well! Thanks for saving me from having to do my own coding. ;-)

    Reply »

    • By Jonathan Dingman on

      Cheers mate, happy to help :) Glad it’s working well for you.

      Reply »

  25. By s3kti on

    how to use it on the genesis, I’ve copy and paste in the child theme functions.php does not work?

    Reply »

    • By Jonathan Dingman on

      Yes, just put the code into your functions.php file.

      What issues are you having with it? Last I tested it, it was working just fine.

      Make sure you’re running the latest version of WordPress as well.

      Reply »

      • By s3kti on

        nothing issue and error, just not working. i have use lates wordpress and genesis framework.
        I have used it previously on the wordpress standard theme, and it works perfectly. But after moving to the genesis of the child theme does not seem to work. whether there is additional code that must added, before I paste it into functions.php?
        I was curious, because you are very good snipshet.

        Reply »

    • By Jonathan Dingman on

      Ben,

      “…breaks my theme…” can you talk about what is actually breaking? That’s a pretty vague statement.

      Did you put it into your functions.php? Are you running WordPress 3.4.1?

      Reply »

      • By on

        Hi. Yes, I put it into my functions.php and then my webiste backend becomes inaccessible. It comes up as a blank white page. When I delete my theme then re-install, it comes back.

        Reply »

        • By Jonathan Dingman on

          You may not be adding the code correctly to your functions.php, make sure it’s inside the < ?php tags.

          Reply »

          • By on

            I’m definitely putting the code inside the right tags. Just to be clear, which functions.php is this going in? My theme’s functions.php or the wp-includes functions.php?

            thanks,

          • By Jonathan Dingman on

            Definitely inside your theme’s functions.php file.

            never touch any core files, including anything under wp-includes or wp-admin, those are meant to stay the same.

  26. By Barbara on

    Hi,
    I need to get this to work for an image uploaded by a custom field from within a custom post type. It doesn’t seem to be locating the image? Any ideas would be appreciated?

    Reply »

    • By Jonathan Dingman on

      Is the custom field actually attaching the image to the post, or is it staying in the custom field? The code above will work for any image that is attached.

      Reply »

      • By Barbara on

        Hi Jonathan,
        Apologies for all the questions but I’m a newbie WP user. I found a piece of javascript which allows the user to upload images using a custom field as this seemed to make the interface more user friendly. It’s saving the image urls in the table ‘wp_postmeta’ under ‘meta_value’ – I assume this means it isn’t attaching them to the post?

        Any ideas how I could get these images to display as thumbs? Should I go about trying to attach them to the post in order to use your script?

        Reply »

  27. By on

    This will not work if the first image is attached via a URL, and not actually on your local file system. Have seen this same problem with several other plugins, ideally, I think there needs to be something to download the image and house it locally for this to work.

    Not in the practice of using other’s images, but my client was, and was using their external URL for about 50 posts. So this was of no help unfortunately on that end, perhaps you could turn it into a plugin to automatically download the store the images, and then update the post automatically on a post by post basis and this would be a much better solution?

    Reply »

    • By Jonathan Dingman on

      Seth,

      You can’t set an external image as a featured image, so yes, it does have to be housed locally on the server file system for it to work.

      This is how WordPress is built, only allowing local images in the media, to be set as a featured image.

      I have other code available which you can look at, which retrives remote images and attaches them to the post if you like. It’s my “How to Download a Video Thumbnail and Set as the Featured Image” plugin code. Feel free to take any of it and modify it for your needs.

      media_handle_sideload() was a huge life-saver with that code. I strongly recommend taking a look at it.

      Reply »

      • By Barbara on

        Hi,
        Sorry when I said it saves the image URL I meant image path, ie ‘http://localhost/dgpp/wordpress/wp-content/uploads/2012/07/pic1.jpg’. It is saving them locally but storing the image path in the wp_postmeta table. Does it need to be entered into the wp_posts table with a post type of “attachment” for this to work?
        Thanks again.

        Reply »

  28. By Pete on

    Can this be modified so that any specific, non-attached image uploaded to my site can be automatically set as the posts’s featured image IF that post has no other images? Make sense?

    Reply »

  29. By on

    Hi, I’ve a question.
    If I reused an image from older post (basically I just copy the html part of the image and paste it in the new post), the featured image won’t show up. How do I reuse old image, and automatically set it as featured image?

    Reply »

    • By Jonathan Dingman on

      As the code is today, it will only set an image that is attached to the post, as the featured image. I’ll try to find some time to look at using any local image that’s in the post, but I’m not sure when it will be ready.

      Reply »

  30. By James on

    Hi – Is it possible to adjust this bit of code to effectively do the opposite?

    I need to be able to grab the featured image url once it’s been uploaded and set as featured image – then put that url into a custom field.

    Reply »

    • By Jonathan Dingman on

      Once you set the featured image, that’s actually how WordPress stores it to begin with.

      The custom field name is: “_thumbnail_id” (no quotes)

      Maybe I’m not understanding what you’re trying to achieve. Can you re-phrase it?

      Reply »

      • By James on

        Hey :)

        What I need to do is grab the URL of the newly added featured image and automatically insert that as a custom field for posts.

        Reply »

        • By Jonathan Dingman on

          As described in my comment, it does this naturally because WordPress actually uses a custom field to hold on to the featured image ID.

          I’m still not sure what you’re looking to do, that it doesn’t already do.

          Reply »

  31. By on

    Hi,
    Is there anyway to set Featured Image from URL without uploading it to our Media Library?

    Reply »

  32. By on

    Hello

    Use ‘transition_post_status’ to avoid multi lines of repeting codes, and do not forget that i can add my own statuses. Kind of :
    function autoset_featured( $new_status, $old_status, $post ) {
    if( $new_status != ‘publish’ ) return;
    $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);
    }
    }
    }
    }
    add_action( ‘transition_post_status’, ‘autoset_featured’, 10, 3 );
    Also, do not use “global post”, you already have “$post” in the 1st paramater.

    See you !

    Reply »

    • By Jonathan Dingman on

      Great idea! Thanks Julio.

      I’ll update the post soon.

      Reply »

    • By on

      Do you know how to make this NOT work on PAGES? i.e.: Not posts.

      I’ve all kinds of ! is_page() return.. etc.. but to no avail.

      Thanks!

      Charles

      Reply »

      • By Jonathan Dingman on

        I would try adjusting this line.

        if (!$already_has_thumb) {

        to be

        if ( is_single() && !$already_has_thumb ) {

        Reply »

  33. By stemie on

    Thanks for this its working.
    Just one thing, some posts have more than one image and its getting the last image of my post, how can I make it fetch the first image (ie the image closest to the title of the post as opposed to the one closest to the end).

    Thanks again

    Reply »

  34. By Chris on

    Took your idea here and extended it for a slightly different angle. I added media to my site who’s name started with a AF- (ie AF-flowers.jpg, AF-baseball.jpg, etc…). As long as the images start with that prefix and the image was not used in a post, (Unattached) the plugin using some of your code and mine, will randomly pick from the images that start with an “AF-” . So just install plugin, upload some images named properly and your good to go.

    Works with auto-blogging as well.

    Plugin Can be Found at http://stcroixsolution.com/auto-feature-plugi/

    Reply »

  35. By Jordan on

    Thanks a bunch for the code, it works exactly as intended.
    Much appreciated.

    Reply »

  36. By on

    Jonathan, first of all, thank you so much for the great coding and for sharing how to set the featured images automatically.

    Could you please let me know if it would be possible to modify the coding for “old” posts, meaning that if an older post didn’t have a featured image to go ahead and use the first image uploaded? If this requires additional coding is it something you would consider adding as a paid feature? If so, how much would this cost? Thank you again for your help!

    Reply »

  37. By Russoroni on

    Hey nice bit of code man. It’s a little more than what I need though. I just want to force authors to set a featured image before publishing. I found this plugin that is super close to what I need… http://wordpress.org/extend/plugins/force-post-title/ Problem is that I am too stupid to write code. How would you feel about whipping up a ‘Force Featured Image’ plugin?

    Reply »

  38. By on

    Hi Jonathan! How do I get this to work in a child theme functions.php file? I’m not the most savvy wordpress user…

    Reply »

  39. By on

    Hi Jonathon,
    I have some posts being fed to the site by a feed. It adds images from the feed, but they are hosted on the other site, not my own. Is there any way I can have the image url from each post be added as the featured image for the post?

    Reply »

    • By nore on

      Did you find any tricks?
      I have the same problem, post are published with a feed and no option for a featured image

      Reply »

  40. By on

    Awesome! Thank you so much for sharing this.. Any code that saves me work in the end is a blessing!

    Reply »

  41. By on

    Wow this fixed my problem so FAST. Love it! I changed themes on my photoblog but I hadn’t ever set the featured image. I always just uploaded a photo from my phone. So when I changed to a theme that used thumb nails on the main page and pulled the featured image, the main page didn’t have any images but this copy paste of the code to the functions.php file worked beautifully. I am amazed.
    THANKS

    Reply »

  42. By on

    Man, that was awesome! Your code is KILLER! Thank you very much for your work!

    Reply »

  43. By on

    I have altered the code a bit and added it to my functions file but it doesn’t seem to be working. I am using a front-end posting system so I’m wondering if it has something to do with that.

    Here is the code I am using if you can provide any assistance.
    Thanks!

    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);
    }
    } else {

    if ( in_category(‘user-audio’) ) {
    foreach ($attached_image as $attachment_id => $attachment) {
    set_post_thumbnail($post->ID, ‘3891’);
    }
    } elseif ( in_category(‘user-video’) ) {
    foreach ($attached_image as $attachment_id => $attachment) {
    set_post_thumbnail($post->ID, ‘3894’);
    }
    } elseif ( in_category(‘user-image’) ) {
    foreach ($attached_image as $attachment_id => $attachment) {
    set_post_thumbnail($post->ID, ‘3892’);
    }
    } elseif ( in_category(‘user-writing’) ) {
    foreach ($attached_image as $attachment_id => $attachment) {
    set_post_thumbnail($post->ID, ‘3895’);
    }
    } elseif ( in_category(‘user-link’) ) {
    foreach ($attached_image as $attachment_id => $attachment) {
    set_post_thumbnail($post->ID, ‘3893’);
    }
    } else {
    foreach ($attached_image as $attachment_id => $attachment) {
    set_post_thumbnail($post->ID, ‘3896’);
    }
    }

    }
    }
    } //end function
    add_action(‘new’, ‘autoset_featured’);
    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’);

    Reply »

    • By Jonathan Dingman on

      Hi Zac,

      It’s possible that you can’t use in_category at that time during the code. That would be my first guess without being able to dive into the code for very long.

      Let me know if you figure it out in a follow-up comment. I probably won’t have much time in the near future to do any debugging on it, sorry.

      Reply »

  44. By on

    man, you are a genius! your little code is doing something that maybe you didn’t think of! every time somebody visits a post it creates the feature image! because of the add_action(‘the_post’… I think.

    nice work!!

    Reply »

  45. By on

    I actually installed the code and was hoping to see the featured image on my iphone but it still doesn’t show up even after I went and resaved the post. Is there something else I need to do.

    Reply »

  46. By J on

    How would I unset / undo all of this? Now all the post show an ugly red cross (on IE) for image not found… :(

    Reply »

    • By Jonathan Dingman on

      J,

      That makes me think there’s an issue with your media manager. I can’t be certain what would cause that to happen, and unfortunately I do not know of a way to “undo” this code — it has always worked in my experience.

      Please do let me know if you find a way to undo it, I’ll be happy to edit the post to include it.

      Reply »

  47. By Andy Smith on

    Hi Jonathan,

    This is a really neat trick. I’m currently using WP 3.5 and Genesis 1.8, developing on localhost and had over 100 posts to update to take advantage of what Genesis can do with a Featured image!

    Thanks for sharing!!
    Andy

    Reply »

  48. By on

    Great tip. now all my posts that do not have a featured image automatically show a featured image. Thanks!

    Reply »

  49. By Norman on

    Any ideas how we can auto make this the authors avatar image as the featured image if there is none selected?

    Possibly replace with: echo get_avatar( get_the_author_email(), ’60’ );

    Thanks!

    Reply »

  50. By Andrew Jonathan on

    Hello, I am not attaching any images in the post. Instead i am using the gallery shortcode [gallery]

    Will your function still work?

    thanks
    Andreas

    Reply »

    • By Jonathan Dingman on

      Andrew,

      This code will only work for images that you have attached to the post. If you’re specifying a [gallery] from another post, it will not work.

      Reply »

  51. By Matt Blank on

    Hi Jonathan,

    Great post. But I’ve got 1000’s of articles with a URL in a custom field to the source of the thumbnail. Is there a setting in functions that can magically convert these URL’s to the featured image?

    Thanks!
    Matt

    Reply »

    • By Jonathan Dingman on

      It should be doable by adding in another line to check to see if that custom field exists and if it does, use that instead.

      Have you given it a shot yet to see if you can do it?

      Reply »

      • By Matt Blank on

        My coding skills aren’t that great I’m afraid, so not really sure what I should put where :s Are you able to help at all please?

        Many thanks!
        Matt

        Reply »

  52. By Sue on

    Hi Jonathan!
    Thank you for the great script! It worked seamlessly (almost :) except that it put the last image in all of my posts as the featured image. Any way to redo that so it pulls the first image? (Each post has 3 images, one at the top, middle, and bottom).
    Thanks again!
    Sue

    Reply »

  53. By on

    Hi, thanks for sharing this .. i use a boot swatch theme with Yet another Photo Blog , with no thumbnail set and the Post is Blank (apart from 1 image uploaded to YAPB) so with all this , can this script work for me ?
    moreover ..
    i have been searching for some “custom field” module ,in which i can just declare the URL of an image as featured image but i cant find that ,so stumbled here ..
    any help please?

    Thanks
    xJ

    Reply »

  54. By on

    Saves a LOT of work, especially when you have a lot of posts… Thanks for the solution!

    Reply »

  55. By Willem-Siebe on

    Hi, I use this script, so many thanks.

    One thing > I just discovered it isn’t working with sub-pages.
    How do I have to change the code to make this work?

    Kind regards,

    Willem

    Reply »

    • By Jonathan Dingman on

      Hi Willem,

      The code was actually developed to only work on Posts, so I haven’t tested it against Pages at all.

      Reply »

      • By Willem on

        Hi,

        Okey, that’s clear. I found a problem with publishing posts also.
        I worked all the time, but when I now upload a picture in the post, I will not take that picture as featured image, but it will take my default featured images for the case I don’t use an image in a post…. Can you have a look into that.

        Do you have any tips, advice how to get this work on sub-pages as well?

        Kind regards,

        Willem

        Reply »

        • By on

          Had the same problem with the posts, here is my solution and it appears to work. It still shows the autoset featured image in the admin panel, but does not show on published pages:

          function autoset_featured() {
          global $post;
          $already_has_thumb = has_post_thumbnail($post->ID);
          $isPage = is_page();
          if (!$already_has_thumb && $isPage == false) {
          $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);
          }
          } else {
          if (is_page()) {
          //do nothing
          } else {
          set_post_thumbnail($post->ID, ‘816’);
          }
          }
          }
          } //end function

          Reply »

          • By Willem on

            Oke thanks.

            @Jonathan, as a follower of your blog I would like to know I you are going to update this snippet again, please see my questions about problem in posts and subpages. ‘No’ is also an answer, but then I know I have to look further.

            Kind regards,

            Willem

  56. By Muhammad on

    Thanks!

    But whenever I try to send a new post I got this error:

    Warning: Cannot modify header information – headers already sent by (output started at /home/algareda/public_html/wp-content/themes/algareda3/functions.php:3119) in /home/algareda/public_html/wp-includes/pluggable.php on line 876

    Reply »

    • By Jonathan Dingman on

      Sounds like you have a whitespace or extra line at the bottom of your functions.php file. This wouldn’t have anything to do with the code above.

      Reply »

  57. By on

    Hi
    Thanks for posting this easy to follow tutorial, I think it will prove very useful when working on large content managed websites in wordpress. It will also help customers manage their websites much more easily and avoid page layout differences if no no featured image has been sent. nice and valuable post.

    Reply »

  58. By on

    You have done a great job. This code will be help for setting images on clients websites. Basically I am not programmer, so I couldnt understand some of the lines in your codes. If you can add explanations to each line of code it would be greatly appreciated. Thanks.

    Reply »

  59. By Helene on

    Hello, thanks for your script Jonathan !

    I am french from Paris and I use wordpress 3.5.1 and in admin I have :

    – 3 errors idem in functions.php : “Notice: Trying to get property of non-object in ”
    – and 1 in Notice: Trying to get property of non-object in wp-includes/post-template.php on line 29

    => Line 29 : function get_the_ID() {return get_post()->ID;}

    and I do not understand why ? Could you help me please, Jonathan ?

    Hélène.

    Reply »

    • By Jonathan Dingman on

      I would try removing the code and re-adding it to your functions.php, I haven’t experienced anything like that error before.

      Reply »

  60. By on

    Hi I want to add featured images to category posts. I want to set different images for different category posts. But I am not PHP programmer, will you please help me. Please send me PHP script for setting a featured image to each category posts. Awaiting your response. Thanks in advance.

    Reply »

  61. By on

    Hi admin, i facing different problem with featured image. My website post taking automatic featured image which is so disgusting for me. How can i stop it? Can you show me proper way to stop featured image, and i want keep option if i want to set then i can.

    Thanks

    Reply »

    • By Jonathan Dingman on

      I’m not quite sure what you mean, Mohsin.

      Can you try rephrasing your question?

      Reply »

  62. By Brand on

    Awesome post, thank you!

    It looks like the second option is made for me. I was wondering how this would work for multisite though as I have hundreds of sites. What would the attachment id be if there are multiple users/sites? Thanks

    Reply »

  63. By on

    Great code snippet! Any tips on setting this up to work with custom post types? I already have post thumbnails enabled but the function only works on standard posts.

    Thanks!

    Reply »

    • By Jonathan Dingman on

      I have an updated version of this code that I’ve been using, which does for CPTs.

      I’ll work on cleaning it up and release it as an update within this post.

      Subscribe to the site’s updates, either via email or RSS, and you’ll see the blog post come through as a new post when I post the big revision.

      Reply »

  64. By Rajeev on

    Hello,

    I just want to add two featured images for Post from front-end.
    Please anyone help me, I think above code is add one featured image for particular post.

    Please guide me how i can add two featured image for one post .
    Thanks in advanced.
    Rajeev

    Reply »

  65. By ben on

    Thank you for posting this code… but can you maybe assist me, to set a feature image for a specific custom post type?

    Thank you!

    Reply »

  66. By Pablo on

    Is there a way to remove the original image (automatically) after doing this?

    Reply »

  67. By on

    Hi Jon

    I moved my site and when I reimported the posts the images are no longer ‘featured’. I need to reset about 800 images to ‘featured’ on old posts and I’m looking for a solution. Does this code work on old posts?

    Tom

    Reply »

    • By Jonathan Dingman on

      Hi Tom,

      The code, as it is right now, does not do that.

      I’ll take that into consideration for a future code update though.

      Reply »

  68. By on

    Hi Jonathan. Is there any possibility I can set a featured image from a third party source like picassa? I really don’t want to upload images in my site that aren’t mine (like gadgets images from Apple) so I thought there might be a way to show the featured image from a url, the url of the image.

    Please help. Thanks a lot! :-)

    Reply »

    • By Jonathan Dingman on

      Yes it is possible.

      You would need to combine the code from another plugin I wrote – http://wordpress.org/plugins/auto-featured-image-for-video-embed/ – which grabs an external image, attaches it to the post, then sets it as the featured image.

      Reply »

  69. By on

    Thank you so much for sharing this code! I had been searching for days for the right plugin to add featured images to old posts so that pictures would automatically show up in my theme. I even used an image caching plugin, but you have to manually cache the images from each source. I have thousands of posts so it had been two days, hours at a time, and still not finished. Then, I add your code to my functions php file, specify the default image and voila! My home page and archive pages all show featured thumbnails instantly, making my blog much more visually appealing. You’ve done such a service posting this. Thank you again!

    Reply »

  70. By on

    HELP PLEASE! I added the code to my functions.php and it assigned featured images to all my posts–however, the featured image looks TERRIBLE with my theme, so I want to remove them. I went back and deleted the code, but it left all of the images. Any ideas? HELP PLEASE!

    Reply »

    • By Jonathan Dingman on

      Erin, you’ll need to go post by post to delete the featured image then.

      Reply »

  71. By David on

    Hi, thank you so much for the snippet and its great to see you responding to comments so long after the original post.

    I have a question like someone above. If the site runs BuddyPress (although I assume it the same if it’s just WordPRess), how could the code be altered to use the members avatar as the featured image rather that just one image on each post or an image from the post?

    Any help would be amazing.

    Reply »

    • By Jonathan Dingman on

      Hi David – I rarely get the chance to work with BuddyPress, so I don’t expect I’ll be able to develop the snippet. However, I would imagine it’s certainly possible and not that difficult.

      If I find the time, I will certainly develop it. Maybe I’ll take it on a weekend project one night.

      Thanks for the idea.

      Reply »

    • By Jonathan Dingman on

      You can add it anywhere in functions.php and it will work.

      Reply »

      • By ben on

        not working on my site , i’m using duena theme, added code but not function

        Reply »

        • By Jonathan Dingman on

          Ben, did you put this code in your functions.php file?

          Reply »

          • By ben on

            yes i did , but still unable , is this code suitable for all type of template?

          • By Jonathan Dingman on

            The code should work with any theme. Can you be a bit more specific to what the problem you’re having is? “Not working” doesn’t exactly describe the problem you’re seeing.

  72. By rajev on

    bro plese help me i serch this for long tim but never get good result but here sounds r good …bo i m confused to whare i add functions.php when i serch i got lots of functions.php so which one i have to choose for editing plese tell here is list

    /public_html/wp-includes/ms-functions.php

    /public_html/wp-includes/functions.php

    /public_html/wp-includes/registration-functions.php

    /public_html/wp-includes/rss-functions.php

    /public_html/wp-content/plugins/wordpress-seo/inc/wpseo-non-ajax-functions.php

    /public_html/wp-content/plugins/wordpress-seo/inc/wpseo-functions.php

    /public_html/wp-content/plugins/facebook-auto-publish/xyz-functions.php

    /public_html/wp-content/themes/twentytwelve/functions.php

    /public_html/wp-content/themes/admired/functions.php

    /public_html/wp-content/themes/admired/widget/widget-functions.php

    /public_html/wp-content/themes/admired/child-starter/admired-child/functions.php

    /public_html/wp-admin/admin-functions.php

    /public_html/wp-admin/upgrade-functions.php

    Reply »

    • By Jonathan Dingman on

      Rajev,

      Based on what you’ve said, my assumption is that you would want to edit this file:

      /public_html/wp-content/themes/admired/child-starter/admired-child/functions.php

      That said, I am assuming that child-starter is your active theme.

      You want to edit the functions.php file in your active theme’s directory.

      Reply »

      • By rajeev on

        not working bro i tried to add code but still postes r not able to select feautre image

        Reply »

      • By rajeev on

        bro tell me code i m confused in both code ..i want to say i m posting eternal image link in my post from imgur thats i want to first image of imgur is set auto feature image for posts plese tell me bro that code in above two codes ..and thanks a lot for reply

        Reply »

        • By Jonathan Dingman on

          Oh ya, that’s the reason it’s not working.

          You can’t set external images as the featured image in WordPress, WordPress doesn’t allow that. You would need to fetch the remote image, save it and attach it to the post, then set it as the featured image.

          Reply »

  73. By on

    Hi Jon,
    what if I am using the Flickr plugin to publish my photos to my post?
    It seems that the plugin is not getting the link from it source, right?

    is there any quick win I can apply in this case?
    Thanks

    Reply »

  74. By Clarissa on

    Implemented this code in about 10 seconds. Just copy/paste the code into functions.php and it worked a charm.

    THANK YOU!!!!

    Reply »

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. [...] 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 [...]

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>