Upload image from a URL and assign it as a Featured Image to a Custom Post Type?

I have it working now, I had tried this code below before posting this question but I was missing the Post ID to assign it to so I just realized that and fixed it and it does work now!

Here is the code just in case it helps someone else in the future…

  $photo_name="testimagename";
  $newId = $post_id;

  // Set Featured Image
  $photo = new WP_Http();
  $photo = $photo->request( $image_url );
  $attachment = wp_upload_bits( $photo_name . '.jpg', null, $photo['body'], date("Y-m", strtotime( $photo['headers']['last-modified'] ) ) );

  $filetype = wp_check_filetype( basename( $attachment['file'] ), null );

  $postinfo = array(
      'post_mime_type'    => $filetype['type'],
      'post_title'        => $title . ' ',
      'post_content'  => '',
      'post_status'   => 'inherit',
  );
  $filename = $attachment['file'];
  $attach_id = wp_insert_attachment( $postinfo, $filename, $newId );
  if( !function_exists( 'wp_generate_attachment_data' ) )
      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 );
  set_post_thumbnail($post_id,$attach_id);

Leave a Comment