Hi,
I have created a custom field for attachment items using the attachment_fields_to_edit
filter which works nicely in the ACF gallery and displays as I would expect.
The issue is, saving of this field doesn’t seem to be handled by ACF as I would expect. It doesn’t actually hook onto the attachment_fields_to_save
method.
Hope you can add this feature/assist me with this 🙂
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
Perfect, does the job and also makes the attachment_fields_to_save hook redundant – thanks!