0

The following code uploads an image which I want to associate with a custom post type.

$upload_overrides = array( 'test_form' => FALSE );
if($file_errors['error'] == 0) {

  if($new_reseller_id = wp_insert_post( $new_reseller_profile_data )){

    //$this->wps_process_image($file, $new_reseller_id);exit;

    $uploaded_file = wp_handle_upload( $file, $upload_overrides );

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

  }
}

The image is uploaded and viewable in the image library but does not appear as the featured image in the custom post type editor. Why is this?

2

I needed to do the following:

set_post_thumbnail( $new_reseller_id, $attach_id );
0

You can also use update_post_meta

// Set Featured Image
update_post_meta($new_reseller_id, '_thumbnail_id', $attach_id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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