I've added a custom meta field to my image details so that a client can add a number to their photos (a design choice). The data would need to show up under each image (like a caption) inserted into the editor when the user inserts into post (I can't use the caption for my purposes because WordPress won't let me nest shortcodes, and I'm using a grid columns plugin which relies on shortcodes).

Found out that you can indeed nest shortcodes—the editor just wasn't inserting the image with caption in the right spot and someone had told me you couldn't nest them. What they meant was that you can't nest the same shortcode: http://codex.wordpress.org/Shortcode_API#Nested_Shortcodes

I'd still like to know if I can add a field that could be specifically for this purpose rather than the caption. Here's what I used to add the custom meta field:

 * Add image number metabox to the media details

function ra_attachment_fields_to_edit($form_fields, $post) {
    $form_fields["image_number"] = array(
        "label" => __("Image Number"),
        "input" => "text", // this is default if "input" is omitted
        "value" => get_post_meta($post->ID, "_image_number", true),
   return $form_fields;
add_filter("attachment_fields_to_edit", "ra_attachment_fields_to_edit", null, 2);

 * Save it
function ra_attachment_fields_to_save($post, $attachment) {
    if( isset($attachment['image_number']) ){
        // update_post_meta(postID, meta_key, meta_value);
        update_post_meta($post['ID'], '_image_number', $attachment['image_number']);
    return $post;
add_filter("attachment_fields_to_save", "ra_attachment_fields_to_save", null , 2);

Use get_post_meta(); in your template to get that metadata attached to that image.

<div class="img-holder">
    <img src="https://dummyimage.com/300x200/bada55/0011ff&text=300x200" alt="">
    <p class="img-number"><?php echo get_post_meta($post->ID, '_image_number', true) ?></p>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.