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:

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...
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...
WordPress automatically adds its current Version number to the head section of the themes. If you view the source of a WordPress-based website, you may find out the WordPress version it is using. Below given is the meta tag that carries that version informatio...