Set Your Featured Image Automagically From the First Image in the Post

Here’s a nifty trick that just came through my RSS reader. Let’s give credit where it’s due first because I didn’t come up with this! It came through my reader from the WP Snippets site, this post right here. We’re going to grab the first image from the post, and set it as your featured image automagically!

You can throw this into fuctions.php, but I put it in my functionality plugin. This is a feature I want in use no matter what theme I’m using! It’s pretty straightforward, you just add this code and you are all set! With this in place, you can insert all the images you want in your post, and the first one will be used as your featured image. But, the cool part is, if you manually set your featured image, it will be used instead. Convenient, no?

// AUTO SET THE FEATURED IMAGE FROM THE 1ST IMAGE IN THE POST
// IF A FEATURED IMAGE IS SET, IT IS USED INSTEAD
function voodoo_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);
                                }
                           }
                        }
      }
add_action('the_post', 'voodoo_autoset_featured');
add_action('save_post', 'voodoo_autoset_featured');
add_action('draft_to_publish', 'voodoo_autoset_featured');
add_action('new_to_publish', 'voodoo_autoset_featured');
add_action('pending_to_publish', 'voodoo_autoset_featured');
add_action('future_to_publish', 'voodoo_autoset_featured');

2 Replies to “Set Your Featured Image Automagically From the First Image in the Post”

    1. Really? Take a look around the site homey. 90% of the problems I’ve had to make solutions myself. Sometimes I find what I need elsewhere and I link to the source (As I did here). The entire point of VoodooPress is for me to track every solution to every problem I’ve come across in case it helps someone else… or me, next time I have the problem.

Leave a Reply