Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins

How to Automatically Remove Products with Specific Shipping Class When Specific Country is Chosen on the WooCommerce Cart/Checkout Page?

As an online store owner, you may have various shipping class products, such as ‘Heavy items’ or ‘Lightweight items.’ You might have such a requirement to limit the shipping of these products to specific countries. The provided code snippets help to prevent products with the shipping class ‘heavy-items’ from being shipped to any country other than the ‘US.’ If another country is selected, the respective product will be automatically removed from the cart.

add_filter( 'woocommerce_package_rates', 'ts_remove_product_from_cart', 10, 2 );
function ts_remove_product_from_cart($rates, $package) {

    foreach( WC()->cart->get_cart() as $key => $item ){

        $product = wc_get_product( $item['product_id'] );
        $product_name = $product->get_title();
        $is_prohibited_product = 'heavy-items' === $product->get_shipping_class();
        $is_shipping_overseas = 'US' !== WC()->customer->get_shipping_country();

        if( $is_prohibited_product && $is_shipping_overseas ){

            wc_add_notice( __( "{$product_name} has been removed from cart because we can't ship that overseas.", 'theme_domain' ), 'error' );

    return $rates;


The output below will showcase two scenarios:

If the customer adds a product with the shipping class ‘heavy-items’ while the shipping country is set to the United States, the code does not apply any restrictions and customer can proceed to checkout as usual.

If the customer attempts to add a product with the shipping class ‘heavy-items’ while selecting a country other than the US (e.g. India), then the specific product is automatically removed from the cart.

Similarly, you can also remove a specific product using its ID or product categories from the cart. Here is the post that will guide you well to remove a product from the WooCommerce cart programatically.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x