This can be done with two filters, attachment_fields_to_edit
and attachment_fields_to_save
, which do exactly what their names suggest. Let’s say you wan to add a source
field. First, generate the field and fill it with its current value if that exists:
function wpse133608_add_attachment_location_field( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'source', true );
$form_fields['source'] = array(
'value' => $field_value ? $field_value : '',
'label' => __( 'Source' ),
'helps' => __( 'Set a source for this attachment' )
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'wpse133608_add_attachment_location_field', 10, 2 );
Then make sure the field is saved if it has content:
function wpse133608add_image_attachment_fields_to_save( $post, $attachment ) {
if ( isset( $attachment['source'] ) )
update_post_meta( $post['ID'], '_source', esc_attr($attachment['source']) );
return $post;
}
add_filter("attachment_fields_to_save", "wpse133608_add_image_attachment_fields_to_save", null , 2);
Read more in this extensive tutorial.