attachment_fields_to_save
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;
}
Changelog
| Since 2.5.0 | Introduced. |
Where the hook is called
attachment_fields_to_save
attachment_fields_to_save
attachment_fields_to_save
wp-admin/includes/media.php 810
$post = apply_filters( 'attachment_fields_to_save', $post, $attachment );
wp-admin/includes/post.php 431
$translated = apply_filters( 'attachment_fields_to_save', $translated, $attachment_data );
wp-admin/includes/ajax-actions.php 3261
$post = apply_filters( 'attachment_fields_to_save', $post, $attachment_data );