I have one particular item that I do not want shipped overseas. Everything else is fine. I already created a shipping class for it and when it gets added to the cart, it has no shipping added to it and the button doesn’t let the customer pay. So, all of this is out-of-the-box in woocommerce. The problem is, when someone overseas wants to buy multiple items and one of them happens to be the one I do not ship overseas. It still adds it to the cart total even though it says it wont be shipped!! See screenshot
I found the code snippet below that I think it’s somewhat the concept of what I need but this one removes a shipping method. I am not a PHP developer or WordPress Codex developer. I’m a front end dev/designer. So, please be gentle lol I do know I don’t want to load my site with plugins for something so simple.
Simply put, I just need the cart to remove any item without a shipping method from the total. So, in my example, it would say $59 in the total ($55 + $4 shipping). The $45 item gets knocked out of the total for not being able to be shipped
add_filter( 'woocommerce_package_rates', 'bbloomer_hide_free_shipping_for_shipping_class', 9999, 2 );
function bbloomer_hide_free_shipping_for_shipping_class( $rates, $package ) {
$shipping_class_target = 15; // shipping class ID (to find it, see screenshot below)
$in_cart = false;
foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
if ( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
$in_cart = true;
break;
}
}
if ( $in_cart ) {
unset( $rates['free_shipping:8'] ); // shipping method with ID (to find it, see screenshot below)
}
return $rates;
}
2
Answers
first of all, find your unique ‘shipping class id’, if you haven’t, figure out what it is from the instructions that it is described in this question best answer.
then you can remove that product from the cart with something like this (put below script in your
function.php
) :Use
woocommerce_package_rates
hook since it is called after user entered their shipping details and that is how you can check whether it is overseas shipping or not. This code also will check each cart item and whether it has specific shipping class slug. If both checks out, then it will remove the item from the cart and shows the notice to the user. Code goes into themefunctions.php
.