Set Featured Image Automatically With PHP Snippets

Set Featured Image Automatically Without Plugin

This small Code Snippets is for those who works in WordPress blog with a picture and at all times wants to put one on his post. It can do the setting automatically. Mean, you can Set Featured Image Automatically with PHP Snippets.

Using featured images in WordPress is easy and comparatively simple to set up even if theme doesn’t support the feature from score.

If you think that option isn’t suit you then you can contrivance different feature swiftly. Contrasting the method mentioned above where WP will inform you about missing featured image where you still need to elect one manually.

This approach will automatically set an image as featured one. To make this work, you will need to have at least one image attached to your post.

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);
  }
}
How to Show or Hide Widgets on Specific Pages without Plugin