Using WordPress ‘attachment_fields_to_save’ PHP filter

The attachment_fields_to_save WordPress PHP filter allows you to modify the attachment fields before they are saved in the database.

Usage

add_filter('attachment_fields_to_save', 'my_custom_attachment_fields_to_save', 10, 2);

function my_custom_attachment_fields_to_save($post, $attachment) {
    // your custom code here
    return $post;
}

Parameters

  • $post (array): An array of post data.
  • $attachment (array): An array of attachment metadata.

More information

See WordPress Developer Resources: attachment_fields_to_save

Examples

Add a custom field to attachment metadata

This example adds a custom field called “credit” to the attachment metadata.

add_filter('attachment_fields_to_save', 'add_credit_to_attachment', 10, 2);

function add_credit_to_attachment($post, $attachment) {
    if (isset($attachment['credit'])) {
        $post['post_excerpt'] = sanitize_text_field($attachment['credit']);
    }
    return $post;
}

Remove certain metadata from the attachment

This example removes the “caption” metadata from the attachment.

add_filter('attachment_fields_to_save', 'remove_caption_from_attachment', 10, 2);

function remove_caption_from_attachment($post, $attachment) {
    $post['post_excerpt'] = '';
    return $post;
}

Change the attachment title

This example modifies the attachment title by adding a prefix.

add_filter('attachment_fields_to_save', 'change_attachment_title', 10, 2);

function change_attachment_title($post, $attachment) {
    $post['post_title'] = 'My Prefix - ' . $post['post_title'];
    return $post;
}

Set attachment alt text based on the title

This example sets the attachment alt text based on the attachment’s title.

add_filter('attachment_fields_to_save', 'set_attachment_alt_text', 10, 2);

function set_attachment_alt_text($post, $attachment) {
    $attachment['image_alt'] = $post['post_title'];
    return $post;
}

Add a custom field to attachment metadata and display it in the media library

This example adds a custom field called “location” to the attachment metadata and displays it in the media library.

add_filter('attachment_fields_to_edit', 'add_location_field', 10, 2);
add_filter('attachment_fields_to_save', 'save_location_field', 10, 2);

function add_location_field($form_fields, $post) {
    $form_fields['location'] = array(
        'label' => 'Location',
        'input' => 'text',
        'value' => get_post_meta($post->ID, '_location', true),
    );
    return $form_fields;
}

function save_location_field($post, $attachment) {
    if (isset($attachment['location'])) {
        update_post_meta($post['ID'], '_location', $attachment['location']);
    }
    return $post;
}