Recently one of our client asked that “How he can edit WooCommerce tax based on the cart value of the customer?” Let say if the cart value is less than X then tax should be X-1 or if cart value id more than X then tax value is X+. How in this article we gonna let you know you can set different tax rates conditionally based on cart item prices in WooCommerce.
Lets say you selling three products on your WooCommerce store which price as below:
- Product A : $200
- Product B : $400
- Product C : $800
So if a customer add all the three products on his/her cart then tax per product will be applied as per the TAX classes you defined in WooCommerce TAX settings. But if you wanna add 5% TAX on cart value is total amount less than or equal to $1000 and 10% TAX if cart value is above $1000 then you can follow the steps below.
Step by Step guide to change WooCommerce tax based on cart value
- Create two WooCommerce TAX class based on requirement in WooCommerce TAX settings. Here i created “GST 12%” and “GST 18%” for example. Click here to know how to create TAX classes in WooCommerce.
- Now open the functions.php file of your Child theme in WordPress theme editor. Create custom function hooked in woocommerce_before_calculate_totals and add below code
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_gst12_tax_rate', 10, 1 );
function apply_conditionally_gst12_tax_rate( $cart ) {
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$defined_amount = 1000;
$subtotal = 0;
foreach ( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_total'];
}
if ( $subtotal >= $defined_amount ){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_item['data']->set_tax_class( 'gst-12' );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_gst5_tax_rate', 10, 1 );
function apply_conditionally_gst5_tax_rate( $cart ) {
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$defined_amount = 1000;
$subtotal = 0;
foreach ( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_total'];
}
if ( $subtotal < $defined_amount ){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_item['data']->set_tax_class( 'gst-5' );
}
}
}
Works and tested on WooCommerce version : 6.5.0
NOTE : Above code will work only if the TAX setting is exclusive of tax, means product prices are exclusive of tax
So that’s all you need to do. Try the code above and let us know how it works.
Happy Coding!
[caldera_form id=”CF60ca2e3ccf64f”]