X

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);
  }
}

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!