Automatically set featured image in WordPress

Using featured images in WordPress is easy and relatively simple to set up even if your theme doesn’t support the feature from scratch. We have already shown you how to set and display the basic featured image and even how to check if there is a featured image set and show a notification to the author who forgot to set one.

If you don’t like that option, you can quickly implement a slightly different feature – you can program your WordPress to set a featured image for you automatically.

Unlike the method mentioned above where WP will notify you about missing featured image where you still need to choose one by yourself, this approach will automatically set an image as featured one. To make this work, you will need to have at least one image attached to your post.

After you publish the post without the featured image, the function will take the first image from that post and set is featured image.

What’s great about this is that once the function sets featured image for you, it will stay on even if you decide to delete the picture from the post (the one function used for making the featured image in the first place).

If you don’t have any pictures attached to your post and you hit publish button, there won’t be any notifications and, of course, there won’t be any images for the function to choose from. So, this is a great option for someone who uses images in most of their posts, but if you tend to forget image more often than not and you don’t attach images on a regular basis, we suggest you check the earlier method of preventing publishing posts without the picture.

Now when you know what you can get with this, let’s show you the code. To install the function, you will have to open your functions.php file and copy/paste the following snippet:

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

Don’t forget to save changes after pasting the code. Now you can try to add a new post with any image inside it and publish it. Do you see how featured image appeared on the site? Magic.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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