how to set an image as featured image of a post with php on Wordpress?

i would like to set an image as featured image of a post. I found this piece of code in the wordpress documentation, it saves the image in the upload directory but the image is not set as featured image of the post (37 in the code) anymore.

Can you please take a look ? thanks a lot

  $wp_filetype = wp_check_filetype(basename($filename), null );
  $wp_upload_dir = wp_upload_dir();
  $attachment = array(
     'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), 
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
  $attach_id = wp_insert_attachment( $attachment, $filename, 37 );
  // you must first include the image.php file
  // for the function wp_generate_attachment_metadata() to work
  require_once(ABSPATH . 'wp-admin/includes/image.php');
  $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
  wp_update_attachment_metadata( $attach_id, $attach_data );


  • As i understand you want to use a image as a featured image on post right ? then why you are not using backend featured image browse option on post. From there you can simply upload image as featured and that featured image you can show with this code on your page the_post_thumbnail( $size, $attr );