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 โBy default, WooCommerce leaves product images in your Media Library even after a product is deleted. While this prevents accidental data loss, it often leads to a bloated server filled with "orphan" images that take up valuable disk space. For shop managers who want an automated workflow, we can hook into the product deletion process. This tutorial shows you how to use the `before_delete_post` hook to identify all associated gallery and featured images and purge them from your server the moment the product is removed.
When you delete a product in WooCommerce, the associated images don't automatically get removed. This is done to prevent data loss. However, you can configure a custom action that deletes the product images upon deletion. Follow this step-by-step guide to set it up on your WooCommerce store.
Step 1: Create a Function to Delete Product Images
First, create a custom function that deletes the images linked to a product. This function will remove both the featured image and gallery images.
function remove_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);
}
}
}
Step 2: Link the Function to Product Deletion
Next, use the before_delete_post hook to trigger the function when a product is deleted.
add_action('before_delete_post', 'remove_product_images');
Step 3: Add the Code to the functions.php File
Add the code to your theme's functions.php file. If you're using a child theme, add it there to preserve the code even during theme updates.
Step 4: Test the Product Deletion
Test the functionality after adding the code. When you delete a product from the WooCommerce admin, its images should be deleted from the server as well.
Important Notes:
External Resources:

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