Search code examples
phpwordpressfunctionwoocommerce

Role based taxes in woocommerce / Cart page


I've set up a woocommerce store with multiple users (B2C & B2B). Some of them will automatically be exempt from tax and just have tax disappear from the cart/checkout. I've used a dynamic pricing plugin to provide different prices to different roles but there is no options for tax variations.

I found this answer and tried to put it in place Role based taxes in woocommerce but as @Jplus2 is telling, @dryan144 solution is not good because it is only applied during the checkout and not on the cart. I tried to figure out the way to do it but I still do have to refresh my 'cart' page to display taxes to 0 (as they are included in the price for "guest" or "customer", any help to launch the action when my cart page is called?

I did the following:

add_filter( 'woocommerce_before_cart_contents', 'prevent_wholesaler_taxes' );
add_filter( 'woocommerce_before_shipping_calculator', 'prevent_wholesaler_taxes' );
add_filter( 'woocommerce_before_checkout_billing_form', 'prevent_wholesaler_taxes' );

function prevent_wholesaler_taxes() {
     global $woocommerce;
     if ( is_user_logged_in() && !(current_user_can('customer'))){
              $woocommerce->customer->set_is_vat_exempt(false);
         } else {
              $woocommerce->customer->set_is_vat_exempt(true);
         }
} //end prevent_wholesaler_taxes

It's working straight away sometimes but most of the time it's only after working after a refresh of my cart which is not good. Try to add https://eshoes.com.au/product/test-shoes08/ to the cart then -> View your basket

Any help would be greately appreciated ;)

Cheers


Solution

  • This solution works perfectly, instead of using set_is_vat_exempt() I simply used $tax)class = 'Zero Rate':

    add_filter( 'woocommerce_before_cart_contents', 'wc_diff_rate_for_user', 1, 2 );
    add_filter( 'woocommerce_before_shipping_calculator', 'wc_diff_rate_for_user', 1, 2);
    add_filter( 'woocommerce_before_checkout_billing_form', 'wc_diff_rate_for_user', 1, 2 );
    add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
    function wc_diff_rate_for_user( $tax_class ) {
    
        if ( !is_user_logged_in() || current_user_can( 'customer' ) ) {
            $tax_class = 'Zero Rate';
        }
        return $tax_class;
    }