/**
* Snippet Name: Delete Product Images on Product Deletion
* Snippet Author: coding-bunny.com
* Description: Deletes the featured and gallery images associated with a WooCommerce product when the product is deleted,
* as long as the images are not used by other products.
*/
add_action( 'before_delete_post', 'cb_delete_product_images', 10, 1 );
/**
* Deletes product images (featured and gallery) when a WooCommerce product is deleted,
* but only if the images are not used by other products.
*
* @param int $post_id The ID of the post being deleted.
*/
function cb_delete_product_images( $post_id ) {
// Verify that the current user has permission to delete products.
if ( ! current_user_can( 'delete_products' ) ) {
return;
}
// Confirm the post is a WooCommerce product.
if ( get_post_type( $post_id ) !== 'product' ) {
return;
}
// Get the WooCommerce product.
$product = wc_get_product( $post_id );
if ( ! $product ) {
return;
}
// Get the featured image ID and gallery image IDs.
$featured_image_id = $product->get_image_id();
$gallery_image_ids = $product->get_gallery_image_ids();
// Delete featured image if it’s not used by other products.
if ( ! empty( $featured_image_id ) && ! cb_is_image_used( $featured_image_id, $post_id ) ) {
wp_delete_attachment( $featured_image_id, true );
}
// Loop through gallery images and delete each if it’s not used by other products.
if ( ! empty( $gallery_image_ids ) ) {
foreach ( $gallery_image_ids as $gallery_image_id ) {
if ( ! cb_is_image_used( $gallery_image_id, $post_id ) ) {
wp_delete_attachment( $gallery_image_id, true );
}
}
}
}
/**
* Checks if an image is used by any WooCommerce product other than the one being deleted.
*
* @param int $image_id The ID of the image attachment.
* @param int $current_product_id The ID of the product currently being deleted.
* @return bool True if the image is used by other products, false otherwise.
*/
function cb_is_image_used( $image_id, $current_product_id ) {
$query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_thumbnail_id',
'value' => $image_id,
'compare' => '='
),
array(
'key' => '_product_image_gallery',
'value' => '"' . $image_id . '"',
'compare' => 'LIKE'
)
),
'post__not_in' => array( $current_product_id ),
'fields' => 'ids',
'posts_per_page' => 1 // Only need to know if there's at least one other product using the image
) );
return $query->have_posts();
}
Delete Product Images on Product Deletion
Deletes the featured and gallery images associated with a WooCommerce product when the product is deleted, as long as the images are not used by other products.