Function and usage of media_post_single_attachment_fields_to_edit() in wordpress


Answers ( 1 )


    The media_post_single_attachment_fields_to_edit() function in WordPress is designed to retrieve and modify the form fields for non-image attachment post types. This function is particularly useful when you need to customize the form fields in the media uploader and attachment editing screens for attachments that are not images, such as documents or audio files.

    Function Signature

    media_post_single_attachment_fields_to_edit( array $form_fields, WP_Post $post ): array


    1. $form_fields (array, required): This parameter is an associative array of attachment form fields. Each form field is an array that can contain various attributes like label, input, value, etc., which define how the form field should be rendered and behave.

    2. $post (WP_Post, required): This is the WP_Post object for the attachment. It provides context about the attachment for which the form fields are being edited, such as its type, current values, and so on.

    Return Value

    • array: This function returns an array of filtered attachment form fields. The returned array should follow the same structure as the $form_fields input but can include modifications or additional fields based on the logic implemented in the function.

    Usage Example

    Let's say you want to add a custom field to the attachment details form for non-image files:

    function my_custom_attachment_fields( $form_fields, $post ) {
        // Add a custom field for non-image attachments
        if ( $post->post_mime_type !== 'image/jpeg' && $post->post_mime_type !== 'image/png' ) {
            $form_fields['my-custom-field'] = array(
                'label' => 'Custom Field',
                'input' => 'text',
                'value' => get_post_meta( $post->ID, '_my_custom_field', true ),
                'helps' => 'Add a custom value'
        return $form_fields;
    add_filter( 'media_post_single_attachment_fields_to_edit', 'my_custom_attachment_fields', 10, 2 );

    In this example, the function my_custom_attachment_fields checks if the attachment is not an image (jpeg or png). If it's not an image, it adds a new custom field (my-custom-field) to the $form_fields array. This custom field is a text input field with a label 'Custom Field'. The value of this field is fetched from the post meta using get_post_meta(). This modified array is then returned, and the new field will appear in the attachment edit screen for non-image files.

Leave an answer