Change Tax in woocommerce using functions.php

  php, woocommerce, wordpress

I am trying to change the tax rate in woocommerce if certain product ID ‘s are in the cart, I found this code and it works I just cant figure out to modify it to check for product ID’s in the cart

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;

$defined_amount = 100;
$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 ) {
$cart_item['data']->set_tax_class( 'zero-rate' );
}
}

Source: Ask PHP

LEAVE A COMMENT