May 7, 2013

Automatically set Featured Thumbnails to WordPress posts

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.

Rahul C.

Rahul C. is a web developer running W3Bits since 2012. He loves making things on the internet and sharing his extensive knowledge about front-end web development.

Want to stay up to date?

Sign up for our email newsletter.

Only the relevant, to-the-point content. Zero spam.