Remove Product Images When Deleting WooCommerce Products
Delete a WooCommerce product's featured image and gallery attachments when the product is permanently deleted.
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
// 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.
Before deleting media automatically, review the site’s broader image optimization workflow and confirm that the attachment is not reused by another product. WooCommerce’s product management documentation explains where product galleries and featured images are maintained.