Within my shop I had to adjust the calculation of the total cart value which was successfull. For this task I used add_action( 'woocommerce_after_calculate_totals', 'custom_woocommerce_after_calculate_totals', 30 );
.
After my calculations I get for example a price of 167,74€ which includes 27,951... VAT (20%).
Now I have the problem that VAT calculation is wrong after a few digits.
The correct result should be 27,956... => rounded up to 27,96. Which results in a cent difference.
Because of the wrong value I tried to do my own calculation by "reverse engineering" the tax rate and calculating the tax_total on my own.
My calculation:
add_action( 'woocommerce_after_calculate_totals', 'custom_woocommerce_after_calculate_totals', 30 );
function custom_woocommerce_after_calculate_totals( $cart ) {
$subtotal = 0.0;
/* Get cart items */
$items = $cart->cart_contents;
$do_one_time = 0;
foreach ($items as $key => $item) {
// Reverse engineer the tax rate because Woocommerce lacks a get rate method on the cart
if($item['line_total'] && $item['line_tax']){
if($do_one_time < 1){
$the_cost = $item['line_total'];
$the_tax = $item['line_tax'];
$tax_rate = round(ceil(($the_tax / $the_cost)*1000)/1000,2);
$do_one_time++;
}
}
/* Calculate cart total value */
if($item["line_subtotal"]){
/* manually add up the cart item subtotal value and round it by 2 digits */
$number = round($item["line_subtotal"], 2);
$subtotal += $number;
}
}
/* If shipping is set add it to subtotal value otherwise keep the already calculated subtotal*/
if($cart->shipping_total){
$subtotal_with_shipping = $cart->shipping_total + $subtotal;
$subtotal_tax = $subtotal_with_shipping * $tax_rate;
$total_cost = round($subtotal_with_shipping + $subtotal_tax, 2);
}else{
$subtotal_tax = $subtotal * $tax_rate;
$total_cost = round($subtotal + $subtotal_tax, 2);
}
/* Compare cart total value with pre-calculated total value by woocommerce */
/* If a difference within the values is present we update the total value with our own total value => $total_cost */
if($subtotal !== $cart->subtotal_ex_tax){
$cart->total = $total_cost;
}
/* part which is not working */
$cart->tax_total = $subtotal_tax;
/* Also tried the following which changes the data within the cart but not on the frontend -> I saw the changes within var_dump($cart)*/
$cart->set_total_tax($subtotal_tax);
}
Within my $subtotal_tax
I have the correct value of 27,96€ but I can´t find a way to update the value.
For the total value I set the $cart->total = $total_cost;
which worked fine.
I tried the same for the total tax with $cart->tax_total = $subtotal_tax;
but I won´t change the value.
Is there some way to update the tax_total wihthin the woocommerce_after_calculate_totals
action?
Output (Wrong):
Total: 167,74€ which includes VAT of 27,95€ (20%).
Output (Needed):
Total: 167,74€ which includes VAT of 27,96€ (20%).