Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

php - 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 :

  • Room A price - 1500
  • Room B Price - 2700
  • Room c price - 2200

GST Tax is set at 12% for rooms wich 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
        if ( $price >= 2500 )
            $cart_item['data']->set_tax_class( 'tax-18' ); // Above 2500
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works on WooCommerce version 3+



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...