1

I am 90% done building a plugin that uses the Amazon.com API. What I have built is a Books Custom Post Type.

My Books CPT has Custom Taxonomies for Book Category, Book Tags, Book Author, and Book Publisher/company

I then have a Settings page that allows you to Import a list of Books from Amazon using there API, you insert the ASIN ID number, 1 per line in a textarea field and then I import each book as a Book CPT and assign the custom taxonomies listed above.

The only thing I am missing at this point is the ability to upload the image that is returned from the Amazon API, I get a URL to the image. I need to upload the image and assign it as the Featured Image for the post it is creating.

I have not been able to find a solution for this yet, can anyone help with some code to upload an image in WordPress from a URL and then assign it as a featured image to a post?

1 Answer 1

1

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);
1
  • function_exists( 'wp_generate_attachment_data' ) was important to fix a RestAPI issue I was facing.
    – brasofilo
    Nov 8, 2020 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.