Code Snippets

Set Featured Image Automatically With PHP Snippets

Riz Ali
Riz
Oct 25, 2017
2 min read
220 words
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);
  }
}
Animated Tooltip with CSS3
Riz Ali

Riz

Author

Riz is a Senior Web Strategist with over 14+ years of hands-on experience in full-stack web design and digital architecture. Having successfully delivered 250+ web projects, he believes passion is the engine of innovation. Riz specializes in translating complex technical concepts into accessible, fanatical content, helping businesses bridge the gap between aesthetic design and high-performance engineering. His work has been instrumental in scaling digital presence for startups and established brands alike.

View all posts

Continue reading

You might also like

Leave a Reply

Your email address will not be published. Required fields are marked *

Menu