Automatically set Featured Thumbnails to WordPress posts

a minute read

WordPress featured thumbnails allow you to add a featured image to your posts. If your WordPress theme has this functionality, then you may set a featured thumbnail to your post by using the Featured Image meta box by clicking the Set Featured image link and uploading your image. The featured thumbnails generally appear in the index pages of your blog along with post body (or excerpt).

Featured image meta box
Featured Image meta box in WordPress Dashboard

But in case when you publish posts frequently and forget setting a thumbnail mostly, you may want them set automatically. In order to achieve that, you need to add the below code in the functions.php file of your WordPress theme and save the changes:

<?php
function auto_featured_thumb() {
  global $post;
  $has_thumb = has_post_thumbnail($post->ID);
  if (!$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', 'auto_featured_thumb');
add_action('save_post', 'auto_featured_thumb');
add_action('draft_to_publish', 'auto_featured_thumb');
add_action('new_to_publish', 'auto_featured_thumb');
add_action('pending_to_publish', 'auto_featured_thumb');
add_action('future_to_publish', 'auto_featured_thumb');
?>

The above code looks into your post for other images added by you, and automatically sets the first image from the post as the featured thumbnail image, if it finds no featured image added to the post.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

When you upload and add images in your WordPress posts, you might have noticed the dimensions that it adds to the image automatically. Same goes with the post thumbnails, they also carry some auto-generated thumbnail markup. The dimension markup is nothing but...
There are times when you need to disable comments on your WordPress site. There are two cases contextual to disabling WordPress comments: Disabling comments for individual posts and pages Disabling comments completely Disabling comments for individual WordPr...
A Content slider allows us to present the content in style, without using much space on our websites. Some of the best examples of the content you would love to put in a content slider are: Featured posts Image Gallery Testimonials There are some cool free p...