By default, WooCommerce does not delete product images when you delete a product. However, this tutorial will guide you on setting up a custom function that removes the product’s images along with the product itself.
Step 1: Create a Function to Delete Images Associated with a Product
Create a custom function that removes both the featured image and the gallery images linked to a product.
function auto_delete_product_images($post_id) { $product = wc_get_product($post_id); if ($product) { $gallery_ids = $product->get_gallery_image_ids(); $featured_image_id = $product->get_image_id(); // Remove featured image if ($featured_image_id) { wp_delete_attachment($featured_image_id, true); } // Remove gallery images foreach ($gallery_ids as $image_id) { wp_delete_attachment($image_id, true); } } }
Step 2: Attach the Function to Product Deletion
Use the before_delete_post
action hook to attach the function to product deletion.
add_action('before_delete_post', 'auto_delete_product_images');
Step 3: Implement the Code in the Theme’s functions.php
File
Insert the code into your theme’s functions.php
file, ideally in a child theme to keep the functionality after future theme updates.
Step 4: Verify the Deletion of Product Images
After adding the function and hook, test the process. When you delete a product from WooCommerce, the related images should also be deleted from your server.
Important Notes:
- Always back up your website before making changes. Deleting product images is permanent.
- Test this on a staging site to ensure it works correctly before applying it to your live website.