Hi all,
When a user deletes an image from the gallery in wp-admin I need it to be deleted from the media library too. I have a function using the acf/update_value hook which works for a normal image field, but doesn’t for the gallery.
function wpse_83587_delete_image( $value, $post_id, $field ) {
$old_value = get_field( $field['name'], $post_id, false );
if ( $old_value && ( int ) $old_value !== ( int ) $value )
wp_delete_attachment( $old_value, true );
return $value;
}
add_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );
Is there a hook they is called when an image gets deleted from the gallery?
Something like
add_filter('acf/update_value/type=gallery', 'remove_gallery_images', 10, 3);
function remove_gallery_images($value, $post_id, $field) {
$images_to_delete = array();
$old_value = get_field($field['name'], $post_id, false);
if (!is_array($old_value)) {
return $value;
}
if (!$value) {
$images_to_delete = $old_value;
} else {
foreach ($old_value as $image_id) {
if (!in_array($image_id, $value)) {
$images_to_delete[] = $image_id;
}
}
}
if (count($images_to_delete)) {
foreach ($images_to_delete as $image_id) {
wp_delete_attachment($image_id, true);
}
}
return $value;
}
but you should be sure that only images that are uploaded to posts can be added to galleries.
Also, when someone is editing content and creates a standard WP gallery, as well as adding images to content and and then having them deleted by one of these functions you’ll get errors in other areas of your site. Hopefully the person that gave you that code warned you about this.