acf_field_gallery::ajax_update_attachment()publicACF 5.0.0

ajax_update_attachment

description

Метод класса: acf_field_gallery{}

Хуки из метода

Возвращает

$post_id. (int)

Использование

$acf_field_gallery = new acf_field_gallery();
$acf_field_gallery->ajax_update_attachment();

Список изменений

С версии 5.0.0 Введена.

Код acf_field_gallery::ajax_update_attachment() ACF 6.0.4

function ajax_update_attachment() {

	// validate nonce
	if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acf_nonce' ) ) {

		wp_send_json_error();

	}

	// bail early if no attachments
	if ( empty( $_POST['attachments'] ) ) {

		wp_send_json_error();

	}

	// loop over attachments
	foreach ( $_POST['attachments'] as $id => $changes ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized by WP core when saved.

		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();
		}

		if ( isset( $changes['title'] ) ) {
			$post['post_title'] = $changes['title'];
		}

		if ( isset( $changes['caption'] ) ) {
			$post['post_excerpt'] = $changes['caption'];
		}

		if ( isset( $changes['description'] ) ) {
			$post['post_content'] = $changes['description'];
		}

		if ( isset( $changes['alt'] ) ) {
			$alt = wp_unslash( $changes['alt'] );
			if ( $alt != get_post_meta( $id, '_wp_attachment_image_alt', true ) ) {
				$alt = wp_strip_all_tags( $alt, true );
				update_post_meta( $id, '_wp_attachment_image_alt', wp_slash( $alt ) );
			}
		}

		// save post
		wp_update_post( $post );

		/** This filter is documented in wp-admin/includes/media.php */
		// - seems off to run this filter AFTER the update_post function, but there is a reason
		// - when placed BEFORE, an empty post_title will be populated by WP
		// - this filter will still allow 3rd party to save extra image data!
		$post = apply_filters( 'attachment_fields_to_save', $post, $changes );

		// save meta
		acf_save_post( $id );

	}

	// return
	wp_send_json_success();

}