attachment_fields_to_edit
Allows you to add a custom field to an image (the field's HTML on the attachment editing screen).
This hook only adds a meta-field; it does not save its data. Use the attachment_fields_to_save hook to save it.
Usage
add_filter( 'attachment_fields_to_edit', 'wp_kama_attachment_fields_to_edit_filter', 10, 2 );
/**
* Function for `attachment_fields_to_edit` filter-hook.
*
* @param array $form_fields An array of attachment form fields.
* @param WP_Post $post The WP_Post attachment object.
*
* @return array
*/
function wp_kama_attachment_fields_to_edit_filter( $form_fields, $post ){
// filter...
return $form_fields;
}
- $form_fields(array)
- The attachment form field data.
- $post(WP_Post)
- The attachment post object.
Examples
#1 Add a meta-field for an image
// Add a meta-field for the image
add_filter( 'attachment_fields_to_edit', 'pon_attachment_fields_to_edit', null, 2 );
function pon_attachment_fields_to_edit( $form_fields, $post ){
$form_fields['carousel_price'] = array(
'label' => 'Price (if needed)',
'input' => '',
'value' => get_post_meta( $post->ID, 'carousel_price', true )
);
return $form_fields;
}
// Save the meta-field data
add_filter("attachment_fields_to_save", "pon_attachment_fields_to_save", null, 2);
function pon_attachment_fields_to_save($post, $attachment) {
if( isset($attachment['carousel_price']) ){
update_post_meta( $post['ID'], 'carousel_price', $attachment['carousel_price'] );
}
else
delete_post_meta( $post['ID'], 'carousel_price' );
return $post;
}
The result:
Changelog
| Since 2.5.0 | Introduced. |
Where the hook is called
attachment_fields_to_edit
wp-admin/includes/media.php 1527
$form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
wp-admin/includes/media.php 1955
$form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
Where the hook is used in WordPress
wp-admin/async-upload.php 86
add_filter( 'attachment_fields_to_edit', 'media_single_attachment_fields_to_edit', 10, 2 );
wp-admin/async-upload.php 96
add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 );
wp-admin/includes/media.php 2398
add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 );
wp-admin/includes/media.php 2621
<?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
wp-admin/includes/media.php 2930
<?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
