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. dhruv bhagat says:

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

    • 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. Incredible Tips! Is it possible mod your script and add a custom field to autosave in _thumbnail_id field?
    Thank you

    • 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. 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. 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. 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?

      • 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. can you guide me where to post this code in function.php???

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

      • 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.

          • 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. 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.

        • 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.

  11. Thanks Jonathan. It works perfectly.

  12. 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. 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.

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

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

        • Jonathan Dingman says:

          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.

          • “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.

  15. 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. 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. 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.

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

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

  19. 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. 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. You know what would be really helpful? Make this a plugin. I’d pay you for it.

    • 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. 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.

  24. 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!

  25. 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!

    • Jonathan Dingman says:

      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.

  26. Thanx, Jonathan. WP 3.3.2 + WP 3.4 RC1 works perfectly.

  27. Fabrizio says:

    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

    • Jonathan Dingman says:

      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

  28. Fabrizio says:

    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

    • Jonathan Dingman says:

      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.

  29. Fabrizio says:

    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!

    • Jonathan Dingman says:

      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.

  30. 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!

    • Jonathan Dingman says:

      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.

  31. 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? :)

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

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

    • Jonathan Dingman says:

      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.

      • 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.

  34. when I implement this into my functions.php it breaks my theme.

    • Jonathan Dingman says:

      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?

      • 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.

        • Jonathan Dingman says:

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

          • 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,

          • Jonathan Dingman says:

            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.

  35. Barbara says:

    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?

    • Jonathan Dingman says:

      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.

      • Barbara says:

        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?

  36. 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?

    • Jonathan Dingman says:

      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.

      • Barbara says:

        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.

  37. 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?

  38. 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?

    • Jonathan Dingman says:

      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.

  39. 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.

    • Jonathan Dingman says:

      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?

      • 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.

        • Jonathan Dingman says:

          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.

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

  41. 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 !

  42. 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

  43. 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/

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

  45. 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!

  46. 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?

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

  48. 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?

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

  50. 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

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

  52. 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’);

    • Jonathan Dingman says:

      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.

  53. Great code! Thank you!!

  54. 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!!

  55. 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.

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

    • Jonathan Dingman says:

      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.

  57. Andy Smith says:

    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

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

  59. 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!

  60. Andrew Jonathan says:

    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

    • Jonathan Dingman says:

      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.

  61. Matt Blank says:

    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

    • Jonathan Dingman says:

      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?

      • Matt Blank says:

        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

  62. 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

  63. 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

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

  65. Willem-Siebe says:

    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

    • Jonathan Dingman says:

      Hi Willem,

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

      • 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

        • 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

          • 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

  66. 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

    • Jonathan Dingman says:

      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.

  67. 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.

  68. 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.

  69. 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.

    • Jonathan Dingman says:

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

  70. 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.

  71. 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

  72. 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

  73. 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!

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

  4. [...] 'autoset_featured'); add_action('future_to_publish', 'autoset_featured'); Source __spr_config={pid:'4e6e1da6c2b2196e0100018d',title:'7 WordPress Hacks You Might Find Useful For [...]

  5. [...] http://wpforce.com/automatically-set-the-featured-image-in-wordpress/ Rate this:Share this:ShareFacebookTumblrTwitterPinterestLike this:LikeBe the first to like this. [...]

  6. [...] code n’est pas le mien ! Voici la source anglophone qui m’a aidé à obtenir le résultat [...]

  7. [...] add_action('future_to_publish', 'autoset_featured');Visto en WPForce Entradas RelacionadasClase 5: El bucle avanzado: query_posts.Reemplazar timthumb por WP Smart Image [...]

  8. [...] منبع لینک مطلب برچسب‌ها: featured image، wordpress، تصویر شاخص، وردپرس [...]

  9. [...] found this code by Johnathan Dingman on WPForce.com. I must say, I would never have thought that this would be so easy to do, but when I saw [...]

Speak Your Mind

*