在woocommerce结帐时添加自定义税值 [英] Add custom tax value at woocommerce checkout
问题描述
我想在woocommerce结帐页面上添加自定义%值,但是我只想在瑞士国家/地区显示它,而对其他国家/地区隐藏它.现在,我可以使用正确的代码了,但是问题是当用户选择瑞士时,Im无法显示它.这是一个代码,所以请帮助我看看我在这里做错了什么
I want to add custom % value at woocommerce checkout page, but I want to show it only for Swiss country and hide it for others. Now I have the right code working for that, but the problems is that Im not able to show it when user choose switzerland. Here is a code so please help me see what Im doing wrong here
//Add tax for CH country
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( WC()->customer->get_shipping_country('CH') )
return;
$percentage = 0.08;
$taxes = array_sum($woocommerce->cart->taxes);
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
// Make sure that you return false here. We can't double tax people!
$woocommerce->cart->add_fee( 'TAX', $surcharge, false, '' );
}
我确定我在这里做错了
if ( WC()->customer->get_shipping_country('CH') )
感谢帮助
推荐答案
WC_Customer
get_shipping_country()
不接受任何国家/地区代码,因为您正在获取国家/地区代码.因此,您需要在代码条件中对其进行不同的设置.
The WC_Customer
get_shipping_country()
doesn't accept any country code as you are getting a country code. So you need to set it differently in your code condition.
由于您的钩子函数已经有WC_Cart对象作为参数,因此不需要全局$woocommerce
和$woocommerce->cart
…
Also as your hooked function has already the WC_Cart object as argument, you don't need global $woocommerce
and $woocommerce->cart
…
因此,您重新访问的代码应为:
So your revisited code should be:
// Add tax for Swiss country
add_action( 'woocommerce_cart_calculate_fees','custom_tax_surcharge_for_swiss', 10, 1 );
function custom_tax_surcharge_for_swiss( $cart ) {
if ( is_admin() && ! defined('DOING_AJAX') ) return;
// Only for Swiss country (if not we exit)
if ( 'CH' != WC()->customer->get_shipping_country() ) return;
$percent = 8;
# $taxes = array_sum( $cart->taxes ); // <=== This is not used in your function
// Calculation
$surcharge = ( $cart->cart_contents_total + $cart->shipping_total ) * $percent / 100;
// Add the fee (tax third argument disabled: false)
$cart->add_fee( __( 'TAX', 'woocommerce')." ($percent%)", $surcharge, false );
}
代码会出现在您活动的子主题(或主题)的function.php文件中,也可能会出现在任何插件文件中.
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
经过测试,可以正常工作……您会得到类似的东西:
Tested and works… you will get something like:
但是对于税收,您最好使用设置>中的默认WooCommerce税收功能.税(标签),其中con可以设置每个国家/地区的税率...
But for taxes, you should better use default WooCommerce tax feature in Settings > Tax (tab), where con can set the tax rates for each country…
这篇关于在woocommerce结帐时添加自定义税值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!