In this post, we’ll look at a simple way to automatically delete product images, including featured and gallery images, whenever a WooCommerce product is removed. This customization will help you to free up storage space on your website, making it run faster and smoother.
Solution: Automatically Delete Image from Media Library When a WooCommerce Product is Deleted
This code snippet ensures that the featured image and product gallery images of a WooCommerce product will be automatically deleted from the WordPress Media library when the product is deleted.
// Automatically Delete Woocommerce Images After Deleting a Product add_action( 'before_delete_post', 'ts_delete_product_images', 10, 1 ); function ts_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 ); } } }
Output
When a product is permanently deleted from your WordPress site, all its associated images are also removed. This helps reduce clutter in your Media Library and improves your site’s performance.
Now you can easily delete a product from your WordPress site, and all its images vanish along with it. This helps keep your Media Library clean and makes your site run faster.