I am trying to change the tax rate in WooCommerce when specific product IDs are in the cart. I found Set 'Zero Tax' for subtotal under $110 - Woocommerce answer code and it works. I just can't figure out how to modify it to check for product ID's in the cart.
Asked
Active
Viewed 789 times
1
-
Some feed back on the answer below will be really appreciated please. – LoicTheAztec Feb 27 '21 at 16:57
1 Answers
1
The following will set "Zero Tax" for specific products if subtotal is under $110 in:
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_zero_tax_rate', 10, 1 );
function apply_conditionally_zero_tax_rate( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$targeted_product_ids = array(37, 53); // Here define your specific products
$defined_amount = 110;
$subtotal = 0;
// Loop through cart items (1st loop - get cart subtotal)
foreach ( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_total'];
}
// Targeting cart subtotal up to the "defined amount"
if ( $subtotal > $defined_amount )
return;
// Loop through cart items (2nd loop - Change tax rate)
foreach ( $cart->get_cart() as $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$cart_item['data']->set_tax_class( 'zero-rate' );
}
}
}
Or the following will set "Zero Tax" when any specific product is in cart and when subtotal is under $110:
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_zero_tax_rate', 10, 1 );
function apply_conditionally_zero_tax_rate( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$targeted_product_ids = array(37, 53); // Here define your specific products
$defined_amount = 110;
$subtotal = 0;
$found = false;
// Loop through cart items (1st loop - get cart subtotal)
foreach ( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_total'];
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$found = true;
}
}
// Targeting cart subtotal up to the "defined amount"
if ( ! ( $subtotal <= $defined_amount && $found ) )
return;
// Loop through cart items (2nd loop - Change tax rate)
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_tax_class( 'zero-rate' );
}
}

LoicTheAztec
- 229,944
- 23
- 356
- 399