wp_get_attachment_metadata returns false with add_action() ‘add_attachment’ hook

The question:

With the following code in functions.php – wp_get_attachment_metadata() returns false and or empty. Perhaps I am attempting to use wp_get_attachment_metadata() before it’s ready? As some tests have shown when manually add a previously added $attachement_ID I get the desired information..

function my_custom_attachment($attachment_ID) {

  $meta = wp_get_attachment_metadata($attachment_id); // returns false

}

add_action('add_attachment', 'my_custom_attachment');

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

add_attachment runs right after an attachment is added to the DB, but but before the metadata is generated. If you don’t need the value to be in the database yet, you can use the wp_generate_attachment_metadata filter to hook in. However, if you need the data to be in the database already, you’ll have to use updated_post_meta and check that the meta_key passed in equals _wp_attachment_metadata.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment