通过WooCommerce中的挂钩有条件地更改产品税类

时间:2019-05-20 21:43:01

标签: php wordpress woocommerce product tax

大约18个月前,我已经在我的WooCommerce商店中实现了b2b区域。最近,我更新了所有插件和wordpress本身。在可变产品上切换税种不再起作用。 到目前为止,以下代码可以正常工作,但是已停止工作。我想念什么?

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;
}

1 个答案:

答案 0 :(得分:0)

要使其正常运行,您最好通过专用的相关复合钩子将WC_Product方法get_tax_class()定位为目标,

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;
}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。


基于WC_Customer is_vat_exempt属性,您也可以尝试使用以下内容:

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 );
    }
}

代码进入活动子主题(或活动主题)的functions.php文件中。