I want to do something simple: do not ship a particular product to Canada.
Here's the easiest way to do it in my opinion: if that particular product is present in the cart, remove Canada from checkout page.
Particular products:
1- https://constructioncovers.com/product/insulated-cement-curing-blankets/ (ID: 12616)
2- https://constructioncovers.com/product/insulated-construction-tarps/ (ID: 15631)
My research:
This article gave me a way to find products in cart and perform any action if condition is true: https://businessbloomer.com/woocommerce-easily-check-product-id-cart/ This article gave me a way to remove specific country from checkout page How to remove specific country in WooCommerce I have combined and modified the two codes to try and accomplish my task. Here's my code:
function unset_country_on_condition( $country ) {
$product_id = 15631;
$product_id_2 = 12616;
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$product_cart_id_2 = WC()->cart->generate_cart_id( $product_id_2 );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
$in_cart_2 = WC()->cart->find_product_in_cart( $product_cart_id_2 );
if ( $in_cart || $in_cart_2 ) {
unset($country["CA"]);
return $country;
}
}
add_filter( 'woocommerce_countries', 'unset_country_on_condition', 10, 1 );
But the above function doesn't work
. It makes the country dropdown empty resulting in a site-wide warning notice.
Can someone point out what I am doing wrong?