Create Custom Menu in WordPress Dashboard
Complete tutorial on create custom menu in wordpress dashboard. Discover practical examples, implementation tips, and expert advice for WordPress and WooCo
Read More →
In WooCommerce, when you delete a product, the product images are not automatically removed from your server. This is a precautionary measure to avoid accidental data loss. However, you can add a custom action to automatically delete product images when a product is deleted. Follow this step-by-step guide to configure this functionality on your WooCommerce store.
First, you need to create a custom function that will delete the images associated with a product. This function will remove both the featured image and any gallery images when the product is deleted.
function 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();
// Delete featured image
if ($featured_image_id) {
wp_delete_attachment($featured_image_id, true);
}
// Delete gallery images
foreach ($gallery_ids as $image_id) {
wp_delete_attachment($image_id, true);
}
}
}
Next, you will need to hook the custom function to the WooCommerce product deletion action. We will use the before_delete_post action hook to trigger this function when a product is deleted.
add_action('before_delete_post', 'delete_product_images');
functions.phpNow that you’ve created the function and hooked it to the product deletion action, you need to add the code to your theme’s functions.php file. If you’re using a child theme, it’s recommended to add the code there to ensure it persists during theme updates.
With the custom function and hook in place, it's time to test the functionality. When you delete a product from the WooCommerce admin, the associated product images should be deleted from the server as well. Make sure to perform this test carefully.
For further reading and additional customization options, check out these helpful resources:

Search our archives or reach out to our team for solutions and expert advice.