I have a custom post type and a metabox with a file input.
I can insert the attachment, but I can’t update the attachment metadata and I don’t know how to fix it because I don’t receive any error.
Here is my code:
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
echo $attach_id;
echo '<pre>';
print_r($filename);
echo '</pre>';
echo '<pre>';
print_r($attach_data);
echo '</pre>';
and here is the output:
96
Array
(
[name] => one.png
[type] => image/png
[tmp_name] => /tmp/phphQ0e2v
[error] => 0
[size] => 144555
)
Array
(
)
As you can see, $attach_data is empty 🙁
From comment:
Let WordPress generate a file path and use that for the next steps:
This is, what finally fixed it for me:
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: