Do it your self hobby code

Woocommerce: Permanently delete images when a product is deleted

When you delete a product, normally images are left in the media gallery. You may wonder how to permanently delete all the images of the product.

This code snippet will help you to automatically delete the images the moment a product is deleted.

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 );
        }
    }
}
add_action( 'before_delete_post', 'delete_product_images', 10, 1 );

Leave a Comment

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