Using WordPress ‘media_single_attachment_fields_to_edit()’ PHP function

The media_single_attachment_fields_to_edit() WordPress PHP function retrieves the single non-image attachment fields to edit form fields.

Usage

media_single_attachment_fields_to_edit($form_fields, $post);

Parameters

  • $form_fields (array) – An array of attachment form fields.
  • $post (WP_Post) – The WP_Post attachment object.

More information

See WordPress Developer Resources: media_single_attachment_fields_to_edit()

Examples

Displaying attachment form fields

This code snippet displays the form fields for a single non-image attachment post.

// Get the attachment post by its ID
$attachment_post = get_post(123);

// Get the form fields for the attachment post
$form_fields = array();
$form_fields = media_single_attachment_fields_to_edit($form_fields, $attachment_post);

// Display the form fields
foreach ($form_fields as $field_key => $field_value) {
    echo "<strong>{$field_value['label']}</strong>: {$field_value['input']}<br>";
}

Adding custom fields

This code snippet adds custom fields to the form fields for a single non-image attachment post.

function my_custom_attachment_fields($form_fields, $post) {
    // Add custom fields
    $form_fields['custom_field'] = array(
        'label' => 'Custom Field',
        'input' => 'text',
        'value' => get_post_meta($post->ID, '_custom_field', true),
    );

    return $form_fields;
}

add_filter('media_single_attachment_fields_to_edit', 'my_custom_attachment_fields', 10, 2);

Removing form fields

This code snippet removes the caption form field for a single non-image attachment post.

function remove_caption_field($form_fields, $post) {
    unset($form_fields['post_excerpt']);
    return $form_fields;
}

add_filter('media_single_attachment_fields_to_edit', 'remove_caption_field', 10, 2);

Modifying form fields

This code snippet modifies the title form field for a single non-image attachment post.

function modify_title_field($form_fields, $post) {
    $form_fields['post_title']['label'] = 'Custom Title';
    return $form_fields;
}

add_filter('media_single_attachment_fields_to_edit', 'modify_title_field', 10, 2);

Displaying form fields in a table

This code snippet displays the form fields for a single non-image attachment post in a table format.

// Get the attachment post by its ID
$attachment_post = get_post(123);

// Get the form fields for the attachment post
$form_fields = array();
$form_fields = media_single_attachment_fields_to_edit($form_fields, $attachment_post);

// Display the form fields in a table
echo '<table>';
foreach ($form_fields as $field_key => $field_value) {
    echo "<tr><td><strong>{$field_value['label']}</strong></td><td>{$field_value['input']}</td></tr>";
}
echo '</table>';