Delete Product Image With Product Delete In WooCommerce

In WooCommerce, when you delete a product, by default, the product images are not automatically deleted from the server to avoid accidental data loss. However, you can add a custom action to delete the product images when a product is deleted. Here’s a step-by-step guide to achieve this:

**Step 1: Create a Custom Function to Delete Product Images**
First, create a custom function to delete the product images associated with a product. This function will remove the images from the server when a 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 need to hook the custom function to the product deletion action in WordPress. You can use the `before_delete_post` action hook to trigger the custom function when a product is deleted.

add_action('before_delete_post', 'delete_product_images');

 

**Step 3: Place the Code in Your Theme’s Functions.php**
Now, add the custom function and the hooking code to your theme’s functions.php file. If you are using a child theme, you can add it to the child theme’s functions.php file.

**Step 4: Test the Deletion**
With the custom function and hook in place, test the product deletion in WooCommerce. When you delete a product from the WooCommerce admin, the associated product images should also be deleted from the server.

Please exercise caution while implementing this code, and take backups of your data before making any changes to your website. Deleting images directly from the server can lead to data loss, so ensure you have tested the functionality thoroughly before deploying it on a live website.

Leave a Comment

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