问题描述
我正在尝试在WooCommerce购物车中自动应用3种不同的优惠券代码.
I'm trying to automatically apply 3 different coupon codes in WooCommerce Cart.
这是我的代码!
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
global $woocommerce;
$coupon_code5 = '5percent';
$coupon_code10 = '10percent';
$coupon_code55 = '15percent';
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
if ( $woocommerce->cart->cart_contents_total >= 50 && $woocommerce->cart->cart_contents_total < 100 && $woocommerce->cart->cart_contents_total != 100 ) {
$woocommerce->cart->add_discount( $coupon_code5 );
} elseif ($woocommerce->cart->cart_contents_total >= 100 && $woocommerce->cart->cart_contents_total < 150 && $woocommerce->cart->cart_contents_total != 150 ) {
$woocommerce->cart->add_discount( $coupon_code10 );
} else {
$woocommerce->cart->add_discount( $coupon_code15 );
}
}
添加5%的折扣后,此代码似乎可以正常工作,但是一旦我超过100欧元,它就不会应用10%的折扣.
This code seems to work when adding the 5percent discount, but once I go over €100 it doesn't apply the 10percent discount.
它只会继续应用5%的折扣.
It just keeps applying the 5percent discount.
更新:
此代码的工作原理就像一个超级按钮.归功于 LouicTheAztek
This code works like a charm. Credit goes to LouicTheAztek
add_action( 'woocommerce_cart_calculate_fees', 'progressive_discount_based_on_cart_total', 10, 1 );
function progressive_discount_based_on_cart_total( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_total = $cart_object->cart_contents_total; // Cart total
if ( $cart_total > 150.00 )
$percent = 15; // 15%
elseif ( $cart_total >= 100.00 && $cart_total < 150.00 )
$percent = 10; // 10%
elseif ( $cart_total >= 50.00 && $cart_total < 100.00 )
$percent = 5; // 5%
else
$percent = 0;
if ( $percent != 0 ) {
$discount = $cart_total * $percent / 100;
$cart_object->add_fee( "Discount ($percent%)", -$discount, true );
}
}
推荐答案
您最好使用以下简单代码,该代码将根据购物车总额添加购物车折扣(此处我们使用的是折价的负费用):
You should better use this simple code below, that will add a cart discount based on cart total amount (Here we use a negative fee which is a discount):
add_action( 'woocommerce_cart_calculate_fees', 'progressive_discount_based_on_cart_total', 10, 1 );
function progressive_discount_based_on_cart_total( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_total = $cart_object->cart_contents_total; // Cart total
if ( $cart_total > 150.00 )
$percent = 15; // 15%
elseif ( $cart_total >= 100.00 && $cart_total < 150.00 )
$percent = 10; // 10%
elseif ( $cart_total >= 50.00 && $cart_total < 100.00 )
$percent = 5; // 5%
else
$percent = 0;
if ( $percent != 0 ) {
$discount = $cart_total * $percent / 100;
$cart_object->add_fee( "Discount ($percent%)", -$discount, true );
}
}
代码会出现在您活动的子主题(或主题)的function.php文件中,也可能会出现在任何插件文件中.
此代码已经过测试并且可以正常工作.
This code is tested and works.
这篇关于基于WooCommerce中购物车总额的渐进式折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!