0

We have a website with images that do not contain any attachment metadata. I set out to create my own function that checks if there is metadata, and if there is not any, it will create it.

Unfortunately, I am afraid that wp_get_attachment_metadata() stays empty all of the time. Or that I can't update the metadata with wp_update_attachment_metadata()

My function is as followed:

function custom_attach_func($attch_id) {
    $meta_data = wp_get_attachment_metadata($attch_id);
    if($meta_data == ''){
        $attachment_path = get_attached_file($attch_id);
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        $attach_data = wp_generate_attachment_metadata( $attch_id, $attachment_path);
        wp_update_attachment_metadata( $attach_id,  $attach_data );
        return $attach_data;
    }else{
        return wp_get_attachment_metadata($attch_id);
    }
}

While wp_generate_attachment_metadata() does generate the metadata, and wp_update_attachment_metadata() returns true, wp_get_attachment_metadata() keeps returning ''.

Is this a Wordpress bug? Am I doing it wrong?!

5
  • 1
    Why require_once( ABSPATH . 'wp-admin/includes/image.php' );? Are you outside of WordPress? Could you provide code and step by step guide to reproduce the issue?
    – cybmeta
    Oct 7, 2016 at 8:50
  • @cybmeta this was needed to let wp_generate_attachment_metadata work properly, check the codex under notes for this. This function is being called while injecting data to the post's content with add_filter ('the_content', 'insertData');
    – xvilo
    Oct 7, 2016 at 10:07
  • That is why I ask about the enviroment where you are using the code; you only need to include core files manually in some rare conditions. Can you describe the enviroment? Other than that, your code seems ok and empty string is a valid value returned wp_get_attachment_metadata(), because the value of a meta field can be a empty string.
    – cybmeta
    Oct 7, 2016 at 10:32
  • I am not sure what you mean with describing the environment. It is being run with the add_filter ('the_content', 'insertData'); from the main plugin file. So it, I think, full within WordPress. It a regular Linux based (apache) webserver...
    – xvilo
    Oct 7, 2016 at 14:38
  • Sorry if I was not clear enough, I mean where, when and how the code is executed. As it is, the problem can not be reproduced with the given code and explanation. For example, when do you exectue custom_attach_func()? What is the value of $attch_id variable and how do you pass it to custom_attach_func()? Is it an attachement post type? And so on .... You can edit the question to add more information.
    – cybmeta
    Oct 7, 2016 at 16:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.