1

I have implemented a b2b area into my WooCommerce Shop about 18 months ago. Recently I have updated all plugins and wordpress itself. Switching the tax class on variable products doesn't work anymore. The code below worked so far, but stopped working. What am I missing?

add_filter('woocommerce_product_get_price', 'switch_price', 99, 2);
add_filter('woocommerce_product_variation_get_price', 'switch_price', 99, 2);
function switch_price($price, $product){

    if(isset($_COOKIE["customerType"])){
      if($_COOKIE["customerType"] == "business"){
          $product->set_tax_class("Zero Rate");
      }
    }

    return $price;
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
jfla
  • 13
  • 3

1 Answers1

1

To make it work, you will better target the WC_Product method get_tax_class() through dedicated related composite hooks, this way:

add_filter('woocommerce_product_get_tax_class', 'switch_product_tax_class', 100, 2 );
add_filter('woocommerce_product_variation_get_tax_class', 'switch_product_tax_class', 100, 2 );
function switch_product_tax_class( $tax_class, $product ){
    if( isset($_COOKIE["customerType"]) && $_COOKIE["customerType"] == 'business' ){
        return "Zero Rate";
    }
    return $tax_class;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


Based on WC_Customer is_vat_exempt property, you could also try to use the following instead:

add_action( 'template_redirect', 'vat_exempt_b2b_customers' );
function vat_exempt_b2b_customers() {
    if( isset($_COOKIE["customerType"]) && $_COOKIE["customerType"] === 'business' 
    && ! WC()->customer->is_vat_exempt() ){
        WC()->customer->set_is_vat_exempt( true );
    }
}

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

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Is there a reference document you have for these hooks, @LoicTheAztec? – ntk4 Dec 01 '20 at 16:02
  • @ntk4 No as they are composite hooks available based on most WC_Product getter methods. – LoicTheAztec Dec 01 '20 at 17:39
  • I'm having troubles using the getter methods, and I was hoping you'd have a good resource for me to reference to learn some more. It would be very similar to this, except it checks product quantity and changes product tax class based on this. I think I'm going to make a new question about this. – ntk4 Dec 02 '20 at 13:38
  • @ntk4 You should better ask a new question with related details, explanations and your own code attempt – LoicTheAztec Dec 02 '20 at 14:03