custom fields for attachments?

Here is a tutorial that shows how to add custom fields to the attachments/media gallery/thickbox/iframe/whatever-you-call it overlay.

I’ve successfully used it, but have not yet taken it much further by adding radio buttons/checkboxes/etc or messed with limiting the changes to particular post types, but that all looks completely doable too.

Here is the code from the link above, just in case it disappears some day:

1) ‘attachment_fields_to_edit’ : We will attach a function to this hook which will do the job of adding a custom field to Media Gallery.

/* For adding custom field to gallery popup */
function rt_image_attachment_fields_to_edit($form_fields, $post) {
    // $form_fields is a an array of fields to include in the attachment form
    // $post is nothing but attachment record in the database
    //     $post->post_type == 'attachment'
    // attachments are considered as posts in WordPress. So value of post_type in wp_posts table will be attachment
    // now add our custom field to the $form_fields array
    // input type="text" name/id="attachments[$attachment->ID][custom1]"
    $form_fields["rt-image-link"] = array(
        "label" => __("Custom Link"),
        "input" => "text", // this is default if "input" is omitted
        "value" => get_post_meta($post->ID, "_rt-image-link", true),
                "helps" => __("To be used with special slider added via [rt_carousel] shortcode."),
    );
   return $form_fields;
}

2) ‘attachment_fields_to_save’ : This in turn will accept and save the user input.

// now attach our function to the hook
add_filter("attachment_fields_to_edit", "rt_image_attachment_fields_to_edit", null, 2);

    function rt_image_attachment_fields_to_save($post, $attachment) {
    // $attachment part of the form $_POST ($_POST[attachments][postID])
        // $post['post_type'] == 'attachment'
    if( isset($attachment['rt-image-link']) ){
        // update_post_meta(postID, meta_key, meta_value);
        update_post_meta($post['ID'], '_rt-image-link', $attachment['rt-image-link']);
    }
    return $post;
}
// now attach our function to the hook.
add_filter("attachment_fields_to_save", "rt_image_attachment_fields_to_save", null , 2);

Leave a Comment