wp_generate_attachment_metadata returning an empty array wp_generate_attachment_metadata returning an empty array wordpress wordpress

wp_generate_attachment_metadata returning an empty array


I've had a similar problem where mime type was missing. Since I use only one mime type, it was fixed by

'post_mime_type' => 'image/jpeg'

After that, it was still not updating the metadata, but forcing the update with "wp_update_attachment_metadata" solved the problem:

$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);wp_update_attachment_metadata($attach_id, $attach_data);


This is, what finally fixed it for me:

apply_filters('wp_handle_upload', array(    'file' => $file_path,     'url' => $file_url,     'type' => $file_type), 'upload');

Explanation: I'm not quite sure why this fixed the error for me, but I assume that this either has something to do with plugins using the wp_handle_upload hook or that the filters add meta-data to the attachment, which otherwise would be missing in the wp_generate_attachment_metadata function.

Full function:

function add_to_media_lib($file_url, $file_path, $parent_post_id){require_once(ABSPATH . 'wp-admin/includes/image.php');require_once(ABSPATH . 'wp-admin/includes/file.php');// Check the type of tile. We'll use this as the 'post_mime_type'.$file_type = wp_check_filetype(basename($file_url), null);// Get the path to the upload directory.$wp_upload_dir = wp_upload_dir();// Prepare an array of post data for the attachment.$attachment = array(    'guid' => $wp_upload_dir['url'] . '/' . basename($file_url),    'post_mime_type' => $file_type['type'],    'post_title' => preg_replace('/\.[^.]+$/', '', basename($file_url)),    'post_content' => '',    'post_status' => 'inherit',    'post_parent' => $parent_post_id);// Insert the attachment.$attach_id = wp_insert_attachment($attachment, $file_url, $parent_post_id);// apply filters (important in some environments)apply_filters('wp_handle_upload', array('file' => $file_path, 'url' => $file_url, 'type' => $file_type), 'upload');// Generate the metadata for the attachment, and update the database record.if ($attach_data = wp_generate_attachment_metadata($attach_id, $file_path)) {    wp_update_attachment_metadata($attach_id, $attach_data);} else {    echo '<div id="message" class="error"><h1>Failed to create PDF-thumbnail Meta-Data</h1><pre>' . print_r($attach_data) . '</pre></div>';}return $attach_id;}


I know the topic is old but I was facing a similar issue and what worked for me was enabling the Crop thumbnail to exact dimensions (normally thumbnails are proportional) under Settings >> Media. I am using the media_handle_sideload() function by the way.