Home » Wordpress » Wordpress Tip and Tricks » How to Set Featured Image automatically in WordPress

Here is way to set featured image automatically in WordPress..

Have a look at below code block,  function which you can place in your function.php of active wordpress theme and its done.

So simplly follow is the steps which I have coded in this wordpress function:

  1. Select all posts
  2. Get first attached images of the posts using get_children() function
  3. Use the set_post_thumbnail() function to set the featured image for the posts.
<?php
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);
  }

}
?>

Here you may find some scope of improvement in code in terms of coding standards but the reason for this is, function have not optimized in those terms. Here you can share any improvements in above code so anyone who uses this may have better help from this article.

Array ( [0] => Wordpress Tip and Tricks )

Leave a comment

0 Comments.

Leave a Reply

You must be logged in to post a comment.