Retrieving Meta from Image Attachment

I currently have added a meta box to the media library popup using the following:

// ADD CUSTOM INFO INSIDE THE MEDIA LIBRARY
function AddLibraryFields( $form_fields, $post ) {

    $Added_META=get_post_meta($post->ID); 

    // SPEED INPUT
    $Speed=$Added_META['Speed'][0];

    $NEW_form_fields['Speed']=array(
       'value' => $Speed ? $Speed : '', 
       'input' => 'html', 
       'label' => __('Speed'),
    'html' => "<input name='attachments[{$post->ID}][Speed]' value='" . $Added_META['Speed'][0] . "' />");

   return array_merge( $form_fields, $NEW_form_fields );
}; 

add_filter( 'attachment_fields_to_edit', 'AddLibraryFields', 10, 2 );

I then save the information in the new fields using:

Read More
// SAVE CUSTOM MEDIA LIBRARY FIELDS
function MediaLibrarySave($attachment_id){
    // SAVE SPEED
    $Speed=$_REQUEST['attachments'][$attachment_id]['Speed'];
    if(isset($Speed))update_post_meta($attachment_id, 'Speed', $Speed);
}; 

add_action( 'edit_attachment', 'MediaLibrarySave' );

All of this seems pretty straightforward, but I’m still really new to this. The above seems to work great, save the info when changed and is specific to each image. Now, I need to be able to access the information inside the SPEED meta field I added, when the user inserts it into the post (I’m assuming this would be the best place to piece it up and convert it into a data-attribute to feed to a jquery plugin?)

Here’s the function I currently have, but I can’t seem to echo the speed meta?

function InsertToPost( $html, $attachment_id, $attachment){
    $attachment = get_post_meta($attachment_id, 'Speed');

    // WOULD USE THE SPEED SETTING HERE TO CONSTRUCT A NEW <IMG STRING WITH DATA-SPEED
    // OR SOMETHING SIMILAR....    

    return $html;
}; 

add_filter('media_send_to_editor', 'InsertToPost', 10, 3);

Basically, I’m wanting to add multiple meta fields to the media library editor so that I’m able to tag each image (like you would with jQuery.data()) and then later retrieve that information and alter it into a single data-attribute for use inside my plugin.

data-plugin='{ “speed” : 500 }’

Hopefully I’m going about this the right way with the media_send_to_editor hook, but I just can’t manage to retrieve the attachment meta from there….

Related posts

Leave a Reply