How would I adjust this to change country available in the Checkout page by Product Category and not specific Products?
I’m attempting this:
/* HIDE U.S. as a country destination if category is "Canada Only" */
add_filter( 'woocommerce_countries', 'products_disable_country', 10, 1 );
function products_disable_country( $countries ) {
if( is_cart() || is_checkout() ) {
$product_cat = array(195);
foreach( WC()->cart->get_cart() as $item ){
if( in_array( $item['product_cat'], $product_cat ) ){
unset($countries["US"]);
return $countries;
}
}
}
return $countries;
}
But no dice yet…
Used this answer code as a base:
Remove a country from allowed countries when specific products are in WooCommerce cart
Edit (Added some screenshots):
Product is Lemon Tarts, categorized as "Canada Only":.
Category ID for that is 195:
Checkout still shows US as an option in the shipping section:
2
Answers
Update (replaced initial "woocommerce_countries" hook)
To check if a product (or an item) is assigned to a product category term, you should use
has_term()
conditional WordPress function like:Code goes in functions.php file of your child theme (or in a plugin). Tested and work.
Related: Remove a country from allowed countries when specific products are in WooCommerce cart
Here’s how you can implement this:
Step 1: Hook into the woocommerce_countries_allowed_countries Filter
You will use the woocommerce_countries_allowed_countries filter to remove a country from the allowed countries list when a specific product category is present in the cart.
Step 2: Check the Cart for the Specific Product Category
You’ll loop through the items in the cart to check if any of them belong to the specific category you’re interested in.
Step 3: Remove the Country
If the category is found in the cart, you remove the country from the allowed countries array.
woocommerce_countries_allowed_countries Filter: This filter modifies the list of allowed billing countries. The second filter, woocommerce_countries_shipping_countries, modifies the shipping countries list.
Category Check: The function is_cart_contains_category() loops through all items in the cart and checks if any belong to the specified category (your-category-slug).
Country Removal: If a product from the specified category is found in the cart, the country (US in this example) is removed from the list of allowed countries.
Customization:
$category_slug: Replace ‘your-category-slug’ with the actual slug of the product category you want to check.
$country_to_remove: Replace ‘US’ with the ISO 3166-1 alpha-2 code of the country you want to remove.
Use Case:
Restrict Shipping: This could be useful if certain products cannot be shipped to specific countries due to regulations, shipping restrictions, or other reasons.
This code should be added to your theme’s functions.php file