Set Featured Image Automatically

This code goes through all posts and sets the featured image to the first image found in the post.

This should not be used in your theme. Only use this once to update all featured images retroactive. If you’re looking for a snippet that sets the featured image on save, here’s a better one.

Code Snippet:

function set_featured_image_for_posts() {
  // Get all posts so set higher number, 
 // you can increase to any number if you have big amount of posts
  $args = array( 'numberposts' => 5000);
  
  // all posts
  $all_posts = get_posts( $args );	
  
  foreach($all_posts as $k=>$v)
  {
    $args = array(
    'numberposts' => 1,
    'order'=> 'ASC',
    'post_mime_type' => 'image',
    'post_parent' => $v->ID,
    'post_type' => 'attachment'
    );	
	
    // Get attachments
    $attachments = get_children( $args );
    $i=0;
    foreach($attachments as $attach)
    {
      // Get only first image
      if($i==0)
        $attachmentsid = $attach->ID;
      $i++;
    }
  
    // Set Featured image
    set_post_thumbnail($v->ID,$attachmentsid);
  }
}

Posted in Images, Posts