Automatic Media Cleanup: Deleting Images with Products

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.

Remove Product Images Automatically on Product Deletion in WooCommerce

Code Snippets Coding Blog Hooks PHP PHP Debugging PHP Snippets Woocommerce WooCommerce Custom Code Woocommerce Hooks Wordpress WordPress Development WordPress Functions WordPress Theme Development WordPress Tips WordPress Tutorials

Remove Product Images Automatically on Product Deletion in WooCommerce Tutorial/Guide

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:

๐Ÿ’ก Have a Coding Problem?

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