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?
I believe the following is happening here:
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 thepost_mime_type
, is being passed with the keytype
. Because of this, no mime type is being saved for the post.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 usemedia_handle_upload()
, which will handle the whole media upload for you.Example based on your code: