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:

To hide featured images on a WordPress page without using list items, you can follow these steps:Open your WordPress dashboard and go to the page where you want to hide the featured image.Click on &#34;Pages&#34; in the left-hand menu and select the desired pa...
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...
Filtering posts by year on WordPress can be achieved by utilizing the built-in functionality of the WordPress CMS. This feature allows you to sort and display posts based on their publish year in a customized manner. Here is a step-by-step guide on how to filt...