在WooCommerce中,我使用以下代码为特定国家(巴勒斯坦)的客户申请优惠券:
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
$coupon_code= "mohannad";
$country="FR";
$state = $woocommerce->customer->get_shipping_country();
if( $woocommerce->cart->applied_coupons === $coupon_code ) {
if ( $state == 'PS' ) {
WC()->cart->apply_coupon( 'MOHANNAD' );
} else {
if( $woocommerce->cart->applied_coupons === $coupon_code )
WC()->cart->remove_coupon( 'MOHANNAD' );
}
}
}
我如何检查在国家变更之前是否应用了优惠券以避免错误?
帮忙吗?
你的代码有点过时,你没有使用右勾拳。也有一些错误。试试下面的命令:
add_action( 'woocommerce_before_calculate_totals', 'country_based_discount' );
function country_based_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$coupon_code = 'mohannad';
$allowed_countries = array('PS');
$is_coupon_applied = in_array( $coupon_code, $cart->get_applied_coupons() );
$is_country_allowed = in_array( WC()->customer->get_shipping_country(), $allowed_countries );
if( ! $is_coupon_applied && $is_country_allowed ) {
$cart->apply_coupon( $coupon_code );
}
elseif( $is_coupon_applied && ! $is_country_allowed ) {
$cart->remove_coupon( $coupon_code );
}
}
代码放在活动子主题(或活动主题)的functions.php文件中。应该可以。
加法-处理最小小计金额(与你的评论相关):
add_action( 'woocommerce_before_calculate_totals', 'country_based_discount' );
function country_based_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$coupon_code = 'mohannad';
$allowed_countries = array('PS');
$min_amount = 120;
$cart_subtotal = WC()->cart->subtotal;
$is_coupon_applied = in_array( $coupon_code, $cart->get_applied_coupons() );
$is_country_allowed = in_array( WC()->customer->get_shipping_country(), $allowed_countries );
if( ! $is_coupon_applied && $is_country_allowed && $cart_subtotal >= $min_amount ) {
$cart->apply_coupon( $coupon_code );
}
elseif( $is_coupon_applied && ! $is_country_allowed && $cart_subtotal < $min_amount ) {
$cart->remove_coupon( $coupon_code );
}
}
应该也可以。