通过 WooCommerce 中的挂钩有条件地更改产品税级 [英] Conditionally change products tax class via hooks in WooCommerce
问题描述
大约 18 个月前,我在我的 WooCommerce 商店中实施了一个 b2b 区域.最近我更新了所有插件和 wordpress 本身.切换可变产品的税种不再有效.下面的代码到目前为止工作,但停止工作.我错过了什么?
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;
}
推荐答案
为了让它工作,你最好通过专用的相关组合来定位 WC_Product
方法 get_tax_class()
钩子,这样:
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;
}
代码位于活动子主题(或活动主题)的 functions.php 文件中.经测试有效.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
基于 WC_Customer
is_vat_exempt
属性,您也可以尝试使用以下代码:
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 );
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中.
Code goes in functions.php file of your active child theme (or active theme).
这篇关于通过 WooCommerce 中的挂钩有条件地更改产品税级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!