The get_attachment_fields_to_edit() WordPress PHP function retrieves the attachment fields to edit form fields.
Usage
To use the function, simply pass the required $post
object and the optional $errors
array as parameters. Here’s an example:
$post = get_post($attachment_id); $errors = array(); $fields = get_attachment_fields_to_edit($post, $errors);
Parameters
$post
(WP_Post) – The attachment post object.$errors
(array) – Optional. An array containing errors. Default is an empty array.
More information
See WordPress Developer Resources: get_attachment_fields_to_edit
Examples
Display attachment fields to edit
This example retrieves the attachment fields and displays them in a table.
$post = get_post($attachment_id); $fields = get_attachment_fields_to_edit($post); echo '<table>'; foreach ($fields as $key => $field) { echo '<tr>'; echo '<td>' . $field['label'] . '</td>'; echo '<td>' . $field['input'] . '</td>'; echo '</tr>'; } echo '</table>';
Add a custom field to the attachment fields
This example demonstrates how to add a custom field to the attachment fields array.
function add_custom_field($fields, $post) { $fields['custom_field'] = array( 'label' => 'Custom Field', 'input' => 'text', 'value' => get_post_meta($post->ID, '_custom_field', true), ); return $fields; } add_filter('attachment_fields_to_edit', 'add_custom_field', 10, 2);
Modify an existing field in the attachment fields
This example modifies the “Description” field’s label in the attachment fields array.
function modify_description_field($fields, $post) { if (isset($fields['post_content'])) { $fields['post_content']['label'] = 'Custom Description'; } return $fields; } add_filter('attachment_fields_to_edit', 'modify_description_field', 10, 2);
Remove a field from the attachment fields
This example removes the “Caption” field from the attachment fields array.
function remove_caption_field($fields, $post) { unset($fields['post_excerpt']); return $fields; } add_filter('attachment_fields_to_edit', 'remove_caption_field', 10, 2);
Save custom field data
This example demonstrates how to save the custom field data when the attachment is updated.
function save_custom_field($attachment_id) { if (isset($_POST['attachments'][$attachment_id]['custom_field'])) { $custom_field = $_POST['attachments'][$attachment_id]['custom_field']; update_post_meta($attachment_id, '_custom_field', $custom_field); } } add_action('edit_attachment', 'save_custom_field');