phpwordpresswoocommercecart

Set different Tax rates conditionally based on cart item prices in WooCommerce


In My WordPress e-commerce web site I use WP Hotel Booking, a plugin for hotel room bookings. The checkout process is done using WooCommerce.

The Issue: We have different rooms with different pricing. For example:

GST Tax is set at 12% for rooms which price is below 2500 and 18% for rooms above 2500.

Since I am using WP Hotel Booking for this custom product (room Management), I am unable to use the Additional Tax Classes option in WooCommerce to set different tax classes.

I need your help in writing a function to check the room value and then decide what tax needs to be set for the given room.

Thanks


Solution

  • This is something accessible and easy.

    1°) you need to create in your WooCommerce Tax settings 2 new Tax classes. In this example I have named that tax classes "Tax 12" and "Tax 18". Then for each of them you will have to set a different percentage of 12% and 18%.

    2°) Now here is a custom function hooked in woocommerce_before_calculate_totals action hook that is going to apply a tax class based on the product price. I don't use the tax class names, but the tax class slugs, that are in lowercase and spaces are replace by a hyphen.

    So Here is that code:

    add_action( 'woocommerce_before_calculate_totals', 'change_cart_items_prices', 10, 1 );
    function change_cart_items_prices( $cart ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        foreach ( $cart->get_cart() as $cart_item ) {
            // get product price
            $price = $cart_item['data']->get_price();
            
            // Set conditionaly based on price the tax class
            if ( $price < 2500 ) {
                $cart_item['data']->set_tax_class( 'tax-12' ); // below 2500
            } elseif ( $price >= 2500 ) {
                $cart_item['data']->set_tax_class( 'tax-18' ); // Above 2500
            }
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin).

    This code is tested and works on WooCommerce version 3+