WordPress Version: 6.3
/**
* Handles updating attachment attributes via AJAX.
*
* @since 3.5.0
*/
function wp_ajax_save_attachment()
{
if (!isset($_REQUEST['id']) || !isset($_REQUEST['changes'])) {
wp_send_json_error();
}
$id = absint($_REQUEST['id']);
if (!$id) {
wp_send_json_error();
}
check_ajax_referer('update-post_' . $id, 'nonce');
if (!current_user_can('edit_post', $id)) {
wp_send_json_error();
}
$changes = $_REQUEST['changes'];
$post = get_post($id, ARRAY_A);
if ('attachment' !== $post['post_type']) {
wp_send_json_error();
}
if (isset($changes['parent'])) {
$post['post_parent'] = $changes['parent'];
}
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 (MEDIA_TRASH && isset($changes['status'])) {
$post['post_status'] = $changes['status'];
}
if (isset($changes['alt'])) {
$alt = wp_unslash($changes['alt']);
if (get_post_meta($id, '_wp_attachment_image_alt', true) !== $alt) {
$alt = wp_strip_all_tags($alt, true);
update_post_meta($id, '_wp_attachment_image_alt', wp_slash($alt));
}
}
if (wp_attachment_is('audio', $post['ID'])) {
$changed = false;
$id3data = wp_get_attachment_metadata($post['ID']);
if (!is_array($id3data)) {
$changed = true;
$id3data = array();
}
foreach (wp_get_attachment_id3_keys((object) $post, 'edit') as $key => $label) {
if (isset($changes[$key])) {
$changed = true;
$id3data[$key] = sanitize_text_field(wp_unslash($changes[$key]));
}
}
if ($changed) {
wp_update_attachment_metadata($id, $id3data);
}
}
if (MEDIA_TRASH && isset($changes['status']) && 'trash' === $changes['status']) {
wp_delete_post($id);
} else {
wp_update_post($post);
}
wp_send_json_success();
}