Modify product price based on price with tax included - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Thursday, March 10, 2022

Modify product price based on price with tax included

I'm building a Woocommerce store and I need to get all the prices with tax included to end in zero (For example, if the original price with tax included is 1234, then I round it to 1240).

Products are imported to my website in bulk (+2800 products) but they have the price without tax. I configured the tax in woocommerce settings and I display prices with tax included in the store.

To fix the "ending in 0" problem, I created a method to change the tax value so the final price ends in 0:

// Calculate tax
function filter_woocommerce_calc_tax( $taxes, $price, $rates, $price_includes_tax, $suppress_rounding ) { 
    $key = array_search('IVA', array_column_keys($rates, 'label')); // find tax with label "IVA"
    $tax = $taxes[$key]; // get the current tax
    $subtotal = $price + $tax; // get the total
    $final = ceil($subtotal / 10) * 10; // modify the total so it ends in 0
    $new_tax = $final - $price; // calculate new tax price
    $taxes[$key] = $new_tax; // update tax in array
    return $taxes; // return new calculated taxes
};
add_filter( 'woocommerce_calc_tax', 'filter_woocommerce_calc_tax', 10, 5 ); 

It works really good, but I figured that if I change the tax price, I'm actually changing the tax rate (%) and I can't do that for legal reasons.

That's why I wanted to change the price of the product without tax instead.

I can use the same method:

$final = ceil($subtotal / 10) * 10; // modify the total so it ends in 0
$new_price = $final - $tax; // new price without tax

But I don't know what hook to use to achieve this.

Is is possible to change the price with hooks and filters?



source https://stackoverflow.com/questions/71414341/modify-product-price-based-on-price-with-tax-included

No comments:

Post a Comment