问题
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, '' );
}
Im sure Im doing wrong inside here:
if ( WC()->customer->get_shipping_country('CH') )
thanks for help
回答1:
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.
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 );
}
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:
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…
来源:https://stackoverflow.com/questions/47379965/add-custom-tax-value-at-woocommerce-checkout