acf_field_gallery::ajax_update_attachment
ajax_update_attachment
description
Method of the class: acf_field_gallery{}
Hooks from the method
Returns
$post_id. (int)
Usage
$acf_field_gallery = new acf_field_gallery(); $acf_field_gallery->ajax_update_attachment();
Changelog
| Since 5.0.0 | Introduced. |
acf_field_gallery::ajax_update_attachment() acf field gallery::ajax update attachment code 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();
}