I have this code where I am trying to check if the cart contains products from BOTH categories; Drinks AND Bundles. If true, then apply the fee of -1.
Currently it is working, but not quite correctly as it is checking whether the cart contains EITHER Drinks OR Bundles.
I need it to check that both of the categories are in the cart, not just one. I am sure it is something simple I am missing?
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Categories in a coma separated array
$categories = array('drinks','bundles');
$fee_amount = 0;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
$fee_amount = -1;
}
// Adding the fee
if ( $fee_amount < 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false );
}
}
CodePudding user response:
You can iterate the loop of $cart->get_cart()
get category using get_the_terms()
and push to an array then you can loop $must_categories
to check both category are available or not.
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Categories in a coma separated array
$must_categories = array('drinks','bundles');
$fee_amount = 0;
$product_cat = array();
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
$terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
foreach ($terms as $term) {
$product_cat[] = $term->slug;
}
}
array_unique( $product_cat );
foreach ( $must_categories as $key => $must_cat ) {
if( in_array($must_cat, $product_cat) ){
$fee_amount = -1;
}else{
$fee_amount = 0;
break;
}
}
// Adding the fee
if ( $fee_amount < 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false );
}
}
Tested and works