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 🙁

2 Answers
2

From comment:

Let WordPress generate a file path and use that for the next steps:

$upload    = wp_handle_upload($filename, array('test_form' => false));
$attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
wp_update_attachment_metadata( $attach_id,  $attach_data ); 

Leave a Reply

Your email address will not be published. Required fields are marked *