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…
Using this code as a base but not familiar enough in php…
Remove Canada from country list when specific products are in cart on Woocommerce
To check if a product (or an item) is assigned to a product category term, you should use has_term()
conditional WordPress function like:
add_filter( 'woocommerce_countries', 'allowed_countries_for_product_category', 10, 1 );
function allowed_countries_for_product_category( $countries ) {
if( is_cart() || is_checkout() ) {
$targeted_terms = array(195); // Here define your category terms
$category_found = false; // Initializing
// Loop through cart items
foreach( WC()->cart->get_cart() as $item ){
// Check if one of the targeted categories is assigned
if( has_term($targeted_terms, 'product_cat', $item['product_id']) ){
$category_found = true; // Tag as found
break; // Stop the loop
}
}
// Remove "US" country if any targeted category is found
if ( $category_found && isset($countries['US']) ){
unset($countries['US']);
}
}
return $countries;
}
Code goes in functions.php file of your child theme (or in a plugin). It should work.