X

Automatically Set the Featured Image

Snippets by IsItWP

Sometimes you don’t have a featured image for a post and you want the first image of your article to be used as the featured image automatically.

Instructions: Add the following code to the functions.php file of your WordPress theme to automatically set the featured image for your posts. If you add a featured image to a post, then it will override this code and display your featured image instead.


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);
                }
            }
        }
}
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');

You may also enjoy removing featured image meta box.

Comments  Leave a Reply

  1. Hi,
    it works perfectly for wordpress posts but not with custom posttypes.
    Do you have any idea to make it work on any custom posttype?

    All the best
    Sebastian

  2. Hello

    I tried this code on Elegantthemes Extra theme and it is not working !

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!