Set Featured Image in WordPress by Code

As I have mentioned in my previous article that I have upgraded the blog design. Hence when I was developing this theme I have to make some operation and it was to set the featured image for all post.

I have image uploaded for all the posts but those images were not set as an featured image or we can say that featured image feature was not implemented in that theme. But in this theme I have planned to use the same. So I had two options at that time.

  1. Manually Set Featured images for all posts
  2. Create some code which sets featured images for all posts

So as a being web developer obviously I have choosen the second option and written one function which selects the image for the posts and assign those image as an featured image.

Let me explain in words, have a look at below steps.

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.

Have a look at below code block for the same, I have created one function which you can place in your function.php of active theme and its done.

function set_featured_image_for_posts() { // Get all posts so set higher number $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); } }
function set_featured_image_for_posts()
{
  // Get all posts so set higher number
  $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 I 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.

Share This Article

  • http://www.arefly.com/ 超級efly

    Hi, good post.
    I just have a question. The code: function set_featured_image_for_posts() seems just a function without any hooks to it. So why will a function work without using it? Thanks