How to Automatically Delete Woocommerce Images After Deleting a Product?

In this video I’m going to show you how to automatically delete Woocommerce images after deleting product. This way you free up server space and reduce media library clutter. One Warning though: If an image is assigned to more than one product then the other product will also lose this image after product deletion.

Paste this code snippet inside your theme’s functions.php file or better yet, use the Code Snippets plugin for it.

// Automatically Delete Woocommerce Images After Deleting a Product
add_action( 'before_delete_post', 'delete_product_images', 10, 1 );

function delete_product_images( $post_id )
{
    $product = wc_get_product( $post_id );

    if ( !$product ) {
        return;
    }

    $featured_image_id = $product->get_image_id();
    $image_galleries_id = $product->get_gallery_image_ids();

    if( !empty( $featured_image_id ) ) {
        wp_delete_post( $featured_image_id );
    }

    if( !empty( $image_galleries_id ) ) {
        foreach( $image_galleries_id as $single_image_id ) {
            wp_delete_post( $single_image_id );
        }
    }
}

Video: How to Automatically Delete Woocommerce Images After Deleting a Product?

Useful Woocommerce related tips

  • 12 useful Woocommerce snippets & hacks

  • How to Show Woocommerce Variations as Single Products?

  • How to create, remove, rename and re-order Woocommerce product tabs?

Leave a Comment

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

Scroll to Top