← Back to notes
snippet 1 min read PHP 7.4+ WP 5.0+ WC 3.0+

Remove Product Images When Deleting WooCommerce Products

Delete a WooCommerce product's featured image and gallery attachments when the product is permanently deleted.

Updated Dec 1, 2025 #woocommerce #wordpress #php #media #snippet

WooCommerce product images can remain in the Media Library after a product is deleted. This hook removes the product’s featured image and gallery attachments when WordPress permanently deletes the product post.

Warning: this permanently deletes the image attachments. Use it only when those images are not shared with other products or pages, and test it on a staging site first.

The snippet

functions.php
// Automatically delete WooCommerce images after deleting a product.
add_action( 'before_delete_post', 'delete_product_images', 10, 1 );
function delete_product_images( $post_id ) {
$product = wc_get_product( $post_id );
if ( ! $product ) {
return;
}
$featured_image_id = $product->get_image_id();
$image_galleries_id = $product->get_gallery_image_ids();
if ( ! empty( $featured_image_id ) ) {
wp_delete_post( $featured_image_id );
}
if ( ! empty( $image_galleries_id ) ) {
foreach ( $image_galleries_id as $single_image_id ) {
wp_delete_post( $single_image_id );
}
}
}

The hook runs before deletion and retrieves the product through WooCommerce’s product API. If you reuse the same media files elsewhere, replace this automatic approach with a review queue or a check for shared attachment usage before deleting.