Automatically Delete Product Images When Deleting in WooCommerce

Delete Product Images Automatically With Product Deletion in WooCommerce

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.

 

Step 1: Create a Custom Function to Delete Product Images

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);
        }
    }
}

Step 2: Hook the Function to Product Deletion

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');

Step 3: Add the Code to Your Theme’s functions.php

Now 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.

Step 4: Test the Product Deletion Process

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.

Important Notes:

  • Always back up your website before making any changes, as deleting product images is permanent.
  • Ensure you thoroughly test this functionality on a staging environment before applying it to your live website.

External Resources:

For further reading and additional customization options, check out these helpful resources:

Scroll to Top

Request A Quote