WordPress Snippets at WPcustoms

Set post image as featured image

This code grabs the first image from your post and inserts it as the featured image. If your post does not contain an image you can specifiy a default image via unique ID. Featured images which are manually set will taken first priority.


/**
 * Snippet Name: Set post image as featured image
 * Snippet URL: https://wpcustoms.net/snippets/set-post-image-as-featured-image/
 */
  function wpc_featured_image() {
          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, '123'); // set your default image ID
                           }
                        }
      }  //end function
	  
add_action('the_post', 'wpc_featured_image');
add_action('save_post', 'wpc_featured_image');
add_action('draft_to_publish', 'wpc_featured_image');
add_action('new_to_publish', 'wpc_featured_image');
add_action('pending_to_publish', 'wpc_featured_image');
add_action('future_to_publish', 'wpc_featured_image');