I am inserting a control in the Wocommerce cart which, based on certain properties of the user and the inserted item, modifies the tax rate for that specific item.
The code I'm using, inside a plugin, is the following:
add_action('woocommerce_before_calculate_totals', 'switch_product_tax_class_in_cart', 10, 1);
/**
* @param $cart
*/
function switch_product_tax_class_in_cart($cart)
{
foreach ($cart->get_cart() as $cart_item) {
if (isUserAgevolabile() && get_field('product_agevolabile', $cart_item['product_id'])) {
$cart_item['data']->set_tax_class('iva-4');
}
}
}
Unfortunately, this doesn't work.
I've also made a test using the function set_price() but this works properly.
Moreover, I already change the tax class in the product listings/product pages in this way, and it works:
add_filter('woocommerce_product_get_tax_class', 'switch_product_tax_class', 1, 2);
add_filter('woocommerce_product_variation_get_tax_class', 'switch_product_tax_class', 1, 2);
/**
* @param $tax_class
* @param $product
* @return mixed
*/
function switch_product_tax_class($tax_class, $product)
{
if (!is_cart() && isUserAgevolabile() && get_field('product_agevolabile')) {
return 'iva-4';
}
return $tax_class;
}
I've solved the problem by editing the second part of the code in this way:
The first part (attached to the action
woocommerce_before_calculate_totals) is no more required.