Home
›
News
Attachment_fields_to_save — Сохраняет произвольное поле добавленное к изображению (вложению) с помощью хука attachment_fields_to_edit. Хук-фильтр WordPress
01.09.2018
Сохраняет произвольное поле добавленное к изображению (вложению) с помощью хука attachment_fields_to_edit .
Срабатывает автосохранение при загрузке изображения например в записях (проверить, потому что не выводится надпись "Сохраняем...")
Использование
add_filter( 'attachment_fields_to_save', 'filter_function_name_2051', 10, 2 );
function filter_function_name_2051( $post, $attachment ){
// filter...
return $post;
}
$post
(массив)
Массив данных вложения (записи).
$attachment
(массив)
Массив мета-данных вложения (записи).
Примеры
#1 Сохраняем данные метаполя
Допустим мы добавили метаполе carousel_price (см. хук attachment_fields_to_edit() ).
// Добавим метаполе для изображения
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' => 'Цена (если нужно)',
'input' => '',
'value' => get_post_meta( $post->ID, 'carousel_price', true )
);
return $form_fields;
}
// Сохраняем данные метаполя
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;
}
Где используется хук
...
if ( isset($send_id) && $attachment_id == $send_id ) {
if ( isset($attachment['post_parent']) )
$post['post_parent'] = $attachment['post_parent'];
}
/**
* Filters the attachment fields to be saved.
*
* @since 2.5.0
*
* @see wp_get_attachment_metadata()
*
* @param array $post An array of post data.
* @param array $attachment An array of attachment metadata.
*/
$post = apply_filters( 'attachment_fields_to_save', $post, $attachment );
if ( isset($attachment['image_alt']) ) {
$image_alt = wp_unslash( $attachment['image_alt'] );
if ( $image_alt != get_post_meta($attachment_id, '_wp_attachment_image_alt', true) ) {
$image_alt = wp_strip_all_tags( $image_alt, true );
// Update_meta expects slashed.
update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
}
}
if ( isset($post['errors']) ) {
$errors[$attachment_id] = $post['errors'];
unset($post['errors']);
}
...
...
if ( empty( $_REQUEST['attachments'] ) || empty( $_REQUEST['attachments'][ $id ] ) )
wp_send_json_error();
$attachment_data = $_REQUEST['attachments'][ $id ];
check_ajax_referer( 'update-post_' . $id, 'nonce' );
if ( ! current_user_can( 'edit_post', $id ) )
wp_send_json_error();
$post = get_post( $id, ARRAY_A );
if ( 'attachment' != $post['post_type'] )
wp_send_json_error();
/** This filter is documented in wp-admin/includes/media.php */
$post = apply_filters( 'attachment_fields_to_save', $post, $attachment_data );
if ( isset( $post['errors'] ) ) {
$errors = $post['errors']; // @todo return me and display me!
unset( $post['errors'] );
}
wp_update_post( $post );
foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) {
if ( isset( $attachment_data[ $taxonomy ] ) )
wp_set_object_terms( $id, array_map( 'trim', preg_split( '/,+/', $attachment_data[ $taxonomy ] ) ), $taxonomy, false );
}
if ( ! $attachment = wp_prepare_attachment_for_js( $id ) )
wp_send_json_error();
...
...
// Attachment stuff
if ( 'attachment' == $post_data['post_type'] ) {
if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) {
$image_alt = wp_unslash( $post_data['_wp_attachment_image_alt'] );
if ( $image_alt != get_post_meta( $post_ID, '_wp_attachment_image_alt', true ) ) {
$image_alt = wp_strip_all_tags( $image_alt, true );
// update_meta expects slashed.
update_post_meta( $post_ID, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
}
}
$attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
/** This filter is documented in wp-admin/includes/media.php */
$post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data );
}
// Convert taxonomy input to term IDs, to avoid ambiguity.
if ( isset( $post_data['tax_input'] ) ) {
foreach ( (array) $post_data['tax_input'] as $taxonomy => $terms ) {
// Hierarchical taxonomy data is already sent as term IDs, so no conversion is necessary.
if ( is_taxonomy_hierarchical( $taxonomy ) ) {
continue;
}
/*
* Assume that a 'tax_input' string is a comma-separated list of term names.
* Some languages may use a character other than a comma as a delimiter, so we standardize on
* commas before parsing the list.
*/
...