0
votes

I have an old WordPress web site. Featured images was not common at that time. so I wrote custom code for thumbnails.

Now I changed my theme, updated WordPress and featured images is a standard for new themes.

I want to set fist (or any) image that uploaded for the post as a featured image for the post.

How can I do that?

Thanks.

I figured it out

function autoset_featured() {
      global $post;
      $already_has_thumb = has_post_thumbnail($post->ID);
          if (!$already_has_thumb)  {
          $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                      if ($attached_image) {
                            foreach ($attached_image as $attachment_id => $attachment) {
                            set_post_thumbnail($post->ID, $attachment_id);
                            }
                       }
                    }
  }  //end function
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

this one is worked for me.

1

1 Answers

1
votes

try this:

$args = array(
            'post_type'     => 'posts',
            'numberposts'   => -1,
        );
    $posts = get_posts($args);
    foreach($posts as $post_temp){
        $args = array(
            'post_type'     => 'attachment',
            'numberposts'   => 1,
            'post_parent'   => $post_temp->id,
            'orderby'       => 'post_date',
            'order'         => 'DESC'
        );
        $attachment = get_posts($args);

        set_post_thumbnail( $post_temp->id, $attachment->id ); 
    }