Sometimes while we are tweaking our WooCommerce catalog we need to remove a lot of products at once. The normal WooCommerce behaviour is to keep all product images on WordPres Media Library, either thumbnails or gallery, when a product is removed. So if you are removing products to save hosting space or inodes, bad luck!, you archieve nothing.
But there is a easy solution. Today we publish a small and simple free plugin for that issue: once a product is removed, all its images are removed as well. If you need to remove more images, like for example images from a custom plugin, you could easilly modify it to remove those as well.
The plugin code is somethin like:
class DropwpImageCleaner { static $instance = false; public static function getInstance() { if ( !self::$instance ) self::$instance = new self; return self::$instance; } private function __construct() { add_action('before_delete_post', [$this, 'deleted_post'], 20, 1); } public function deleted_post($post_id) { $post_type = get_post_type( $post_id ); if ( !in_array( $post_type, ['product', 'product_variation']) ) { return; } $product = wc_get_product( $post_id ); if (!$product) { return; } $thumb_id = $product->get_image_id(); $gallery_ids = $product->get_gallery_image_ids(); if ($thumb_id) { $gallery_ids = array_merge( $gallery_ids, [$thumb_id] ); } foreach ( $gallery_ids as $attachment_id ) { wp_delete_attachment( $attachment_id, true ); } } } $dropwpCleaner = DropwpImageCleaner::getInstance();
If you need to remove more elements, you just need to add them to the $gallery_ids array before remove them all at line 33.
You have the plugin at: Dropwp Image Cleaner