I have a scenario here.
In a WooCommerce shop I have setup, a product category 'Bronx'
is a parent category and 'Baby Items Bronx'
is a child category of it. Here Parent category name Bronx is the city where the products under 'Baby Items Bronx'
are sold from.
Another product category 'Newark'
is a parent category and 'Baby Items Newark'
is a child category of it. Here Parent category name Newark is the city where the products under 'Baby Items Newark'
are sold from.
A customer from Bronx is trying to buy the products in 'Baby Items Newark'
category.
I am trying to set up a custom shipping fee in WooCommerce where it can calculate shipping fee based on customer's location and add a custom delivery fee. I was able to achieve to add the fee if the customer choose the city as Bronx in the billing address with this code.
function from_to_city_add_checkout_fee() {
if (($_POST['city']=='Bronx')){
WC()->cart->add_fee( 'Delivery Fee', 15 );
}
Now I need a function that can calculate the fee if the customer is from Bronx and trying to buy products that is listed under parent category is 'Newark'
I tried the following code and it does not work.
function from_to_city_add_checkout_fee() {
if (($_POST['city']=='Bronx') && (has_term( array( 'baby-items-newark' ), 'product_cat' ))){
WC()->cart->add_fee( 'Fee', 150 );
}
}
I tried doing something like this with the code snippet that I got from https://businessbloomer.com/woocommerce-check-product-category-cart/ that helps check what product category is in the cart, it still does not work.
add_action('woocommerce_before_cart', 'bbloomer_check_category_in_cart');
function bbloomer_check_category_in_cart() {
// Set $cat_in_cart to false
$cat_in_cart = false;
// Loop through all products in the Cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// If Cart has category "download", set $cat_in_cart to true
if ( has_term( 'baby-items-newark', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
// Do something if category "download" is in the Cart
if ( $cat_in_cart == true) {
// For example, print a notice
// Or maybe run your own function...
function from_to_city_add_checkout_fee() {
if (($_POST['city']=='Bronx')){
WC()->cart->add_fee( 'Delivery Fee', 150 );
}
}
}
Any help is appreciated.