Skip to content

How To Automatically Set The Featured Image In WordPress

WordPress has a featured image option which allows the author to pick the post thumbnail of the post. Your featured post will be used on your theme, feed and various places. Every major blogging platform has this feature in it but with WordPress, you can take it to the next level.

If you don’t like manually picking featured image for every single post of your blog, then you can automatically set the featured image of the post. This snippet from WPForce will automatically set the first image of your as the featured image. If there’s no images in the entire post, then it has an option to set a default featured image.

Add following snippet to your functions.php file:

function wpforce_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);
                                }
                           } else {
                                set_post_thumbnail($post->ID, '414');
                           }
                        }
      }  //end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

Replace 414 in the 11th line of the above code from the attachment id of your default image.

Leave a Reply

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