attachment_fields_to_savefilter-hookACF 2.5.0

This is a WordPress - attachment_fields_to_save hook. The plugin just uses it.

Saves a custom field added to an image (attachment) using the attachment_fields_to_edit hook.

Fires when an attachment is saved, for example, when image data is saved.

Usage

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

/**
 * Function for `attachment_fields_to_save` filter-hook.
 * 
 * @param array $post       An array of post data.
 * @param array $attachment An array of attachment metadata.
 *
 * @return array
 */
function wp_kama_attachment_fields_to_save_filter( $post, $attachment ){
	// filter...
	return $post;
}
$post(array)
An array of attachment (post) data.
$attachment(array)
An array of attachment (post) metadata.

Examples

#1 Save meta-field data

Suppose we added the carousel_price meta-field (see the attachment_fields_to_edit() hook).

// Add a meta-field for the image
add_filter( 'attachment_fields_to_edit', 'pon_attachment_fields_to_edit', null, 2 );
function pon_attachment_fields_to_edit( $form_fields, $post ){

	$form_fields['carousel_price'] = array(
		'label' => 'Price (if needed)',
		'input' => '',
		'value' => get_post_meta( $post->ID, 'carousel_price', true )
	);

	return $form_fields;
}

// Save the meta-field data
add_filter("attachment_fields_to_save", "pon_attachment_fields_to_save", null, 2);
function pon_attachment_fields_to_save($post, $attachment) {
	if( isset($attachment['carousel_price']) ){
		update_post_meta( $post['ID'], 'carousel_price', $attachment['carousel_price'] );
	}
	else
		delete_post_meta( $post['ID'], 'carousel_price' );

	return $post;
}

Where the hook is called

acf_field_gallery::ajax_update_attachment()
attachment_fields_to_save
acf/pro/fields/class-acf-field-gallery.php 195
$post = apply_filters( 'attachment_fields_to_save', $post, $changes );

Where the hook is used in Advanced Custom Fields PRO

acf/includes/forms/form-attachment.php 35
add_filter( 'attachment_fields_to_save', array( $this, 'save_attachment' ), 10, 2 );