Set the first image in a WP post to the Featured Image if a Featured Image hasn't been set

October 20, 2021
Code Category:

This snippet automatically sets the featured image by fetching the first image of the WordPress post.

*Note – if you choose a featured image, that will be displayed instead.

function autoset_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);
      }
    }
  }
}
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

This will need to be placed in a theme's functions.php file, or, if you're like me, just use the Code Snippets Pro plugin.

©2021 Fotan Web Design