5
        foreach ($_FILES as $key => $file) {
            $uploadedImage = wp_handle_upload($_FILES[$key], $upload_overrides);

            pre_r($uploadedImage);

            if (!isset($uploadedImage['error'])) {

                $attachID = wp_insert_attachment($uploadedImage, $uploadedImage['file']);

                require_once(ABSPATH . 'wp-admin/includes/image.php');
                $attach_data = wp_generate_attachment_metadata( $attachID, $uploadedImage['file'] );

                print_r($attach_data);

                wp_update_attachment_metadata( $attachID, $attach_data );

            } else {

            }
        }

Im almost positive this code should work. I have looked around and people were saying once the added the require_once this worked.

The upload works, the file is added to the media library but no metadata is generated.

Any suggestions?

1

1 Answer 1

2

I believe the following is happening here:

  1. As @Luke pointed out, wp_insert_attachment() takes an array of post data. The format of the array you are passing to it is not correct. The keys are different. What should be stored as the post_mime_type, is being passed with the key type. Because of this, no mime type is being saved for the post.
  2. wp_generate_attachment_metadata() is looking for the mime type so it can generate the metadata based on that. But since the mime type wasn't saved correctly it just returns an empty array.

The solution is to do $uploadedImage['post_mime_type'] = $uploadedImage['type'], or better yet use media_handle_upload(), which will handle the whole media upload for you.

Example based on your code:

foreach ( $_FILES as $key => $file ) {
    media_handle_upload( $key, 0, array(), $upload_overrides );
}

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .