Support

Account

Home Forums Feature Requests WordPress filter attachment_fields_to_save Reply To: WordPress filter attachment_fields_to_save

  • You need to use the edit_attachment action to save those custom fields.

    add_action( 'edit_attachment', 'my_save_attachment_location' );

    Just tested it and it works, wasn’t working with attachment_fields_to_save filter.

    
    function my_add_attachment_location_field( $form_fields, $post ) {
        $field_value = get_post_meta( $post->ID, 'location', true );
        $form_fields['location'] = array(
            'value' => $field_value ? $field_value : '',
            'label' => __( 'Location' ),
            'helps' => __( 'Set a location for this attachment' )
        );
        return $form_fields;
    }
    add_filter( 'attachment_fields_to_edit', 'my_add_attachment_location_field', 10, 2 );
    
    function my_save_attachment_location( $attachment_id ) {
        if ( isset( $_REQUEST['attachments'][$attachment_id]['location'] ) ) {
            $location = $_REQUEST['attachments'][$attachment_id]['location'];
            update_post_meta( $attachment_id, 'location', $location );
        }
    }
    add_action( 'edit_attachment', 'my_save_attachment_location' );
    

    Source