Remove Product Images Automatically on Product Deletion in WooCommerce

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:
  • Always backup your site before making changes, as deleting product images is permanent.
  • Test this functionality on a staging site before implementing it on your live site.

 

External Resources:

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.