php – 基于WooCommerce中购物车总额的累进折扣

我正在尝试在WooCommerce Cart中自动应用3种不同的优惠券代码.

这是我的code

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%的折扣.

它只是继续应用5%的折扣.

更新:

这段代码就像一个魅力.信用到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 );
    }
}

解决方法:

Using multiple coupons with different cart percentage discount is a nightmare as you have to handle when customer add new items, remove items, change quantities and add (or remove) coupons…

您最好使用下面这个简单的代码,根据购物车总金额添加购物车折扣(这里我们使用负折扣,这是一个折扣):

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文件中,或者放在任何插件文件中.

此代码经过测试和运行.

上一篇:spingcloud请求路由本地全流程


下一篇:决策树