如何动态修改店铺位置为客户账单地址获取结账准确税费?是否有对应hook?
实现动态修改店铺位置计算税费的解决方案
如果你使用的是WooCommerce平台,可以通过内置filter hook实现该需求,无需修改核心代码。
核心可用Hook
用到的核心钩子是woocommerce_get_base_location,该钩子会在系统读取店铺默认地址时触发,你可以在结账/购物车场景下将返回的店铺地址替换为客户的账单地址,实现税费按客户所在地计算。
功能实现代码
add_filter( 'woocommerce_get_base_location', 'dynamic_replace_shop_location_with_billing_address', 10, 2 ); function dynamic_replace_shop_location_with_billing_address( $default_location, $tax_class ) { // 仅在购物车、结账页面生效,避免影响后台其他业务逻辑 if ( ( is_cart() || is_checkout() ) && WC()->customer ) { // 获取客户账单地址信息 $default_location = array( 'country' => WC()->customer->get_billing_country(), 'state' => WC()->customer->get_billing_state(), 'postcode' => WC()->customer->get_billing_postcode(), 'city' => WC()->customer->get_billing_city() ); } return $default_location; }
注意事项
- 上述代码需要放入当前站点主题的
functions.php文件,或者自定义功能插件的代码文件中 - 使用前请确认WooCommerce税费设置已经开启了「基于店铺地址计算税费」选项,否则该钩子不会触发
- 若需要按客户配送地址计算税费,将代码中所有
get_billing_xxx方法替换为get_shipping_xxx即可
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

