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

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()->cart->remove_cart_item($key);

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

    return $rates;
}
flexi bogo cta banner image


This to the shop owners who are running or planning to run BOGO offers on their WooCommerce store…

BOGO deals are great for increasing your sales, but have you thought about which offers are bringing you more revenue and which offers are not performing that great?

Don’t just set a BOGO deal, track the revenue generated by your deals in real-time with the Flexi BOGO for WooCommerce plugin.

Output

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:

Subscribe
Notify of
0 Comments
Newest
Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x