The attachment_fields_to_edit WordPress PHP filter allows you to modify the array of attachment form fields in the media library.
Usage
add_filter('attachment_fields_to_edit', 'your_function_name', 10, 2); function your_function_name($form_fields, $post) { // your custom code here return $form_fields; }
Parameters
$form_fields
(array): An array of attachment form fields.$post
(WP_Post): The WP_Post attachment object.
More information
See WordPress Developer Resources: attachment_fields_to_edit
Examples
Add a custom text field to attachment form fields
add_filter('attachment_fields_to_edit', 'add_custom_text_field', 10, 2); function add_custom_text_field($form_fields, $post) { $form_fields['custom_text'] = array( 'label' => 'Custom Text', 'input' => 'text', 'value' => get_post_meta($post->ID, '_custom_text', true), ); return $form_fields; }
Remove the caption field from attachment form fields
add_filter('attachment_fields_to_edit', 'remove_caption_field', 10, 2); function remove_caption_field($form_fields, $post) { unset($form_fields['post_excerpt']); return $form_fields; }
Change the label of the description field
add_filter('attachment_fields_to_edit', 'change_description_label', 10, 2); function change_description_label($form_fields, $post) { $form_fields['post_content']['label'] = 'Custom Description'; return $form_fields; }
Make the alt text field required
add_filter('attachment_fields_to_edit', 'make_alt_text_required', 10, 2); function make_alt_text_required($form_fields, $post) { $form_fields['_wp_attachment_image_alt']['required'] = true; return $form_fields; }
Add a custom dropdown field to attachment form fields
add_filter('attachment_fields_to_edit', 'add_custom_dropdown_field', 10, 2); function add_custom_dropdown_field($form_fields, $post) { $options = array( 'option1' => 'Option 1', 'option2' => 'Option 2', 'option3' => 'Option 3', ); $form_fields['custom_dropdown'] = array( 'label' => 'Custom Dropdown', 'input' => 'html', 'html' => build_dropdown('custom_dropdown', $options, get_post_meta($post->ID, '_custom_dropdown', true)), ); return $form_fields; } function build_dropdown($name, $options, $selected) { $dropdown = "<select name='attachments[{$post->ID}][{$name}]'>"; foreach ($options as $value => $label) { $dropdown .= "<option value='{$value}'" . selected($selected, $value, false) . ">{$label}</option>"; } $dropdown .= "</select>"; return $dropdown; }