Add custom field to image editor

To add a custom field to attachments, place the following code in your functions.php.

add_filter('attachment_fields_to_edit', 'edit_media_custom_field', 11, 2 );
add_filter('attachment_fields_to_save', 'save_media_custom_field', 11, 2 );

function edit_media_custom_field( $form_fields, $post ) {
    $form_fields['custom_field'] = array( 'label' => 'Custom Field', 'input' => 'text', 'value' => get_post_meta( $post->ID, '_custom_field', true ) );
    return $form_fields;
}

function save_media_custom_field( $post, $attachment ) {
    update_post_meta( $post['ID'], '_custom_field', $attachment['custom_field'] );
    return $post;
}

To output that data you can use the following in the loop:

get_post_meta( get_the_ID(), '_custom_field', true ) );

Leave a Comment