问题描述
在 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,$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 );
}
}
它也应该有效。