首页 > 解决方案 > 基于 Woocommerce 中购物车总数的折扣

问题描述

我会尝试根据 3 种不同的方式更改折扣百分比

例如:

  1. 如果客户花费 >= 200.000 他们将有 10% 的折扣
  2. 如果 cosutumer 花费 >= 350.000 他们将获得 15% 的折扣
  3. 如果客户花费 >= 500.000 他们将获得 20% 的折扣

问题是如何在所选产品中应用此折扣?以及如何制作手册,我的意思是当客户在可用列中输入优惠券代码时折扣有效?

这是我到目前为止的代码

add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_total', 
25, 1 );
function discount_based_on_total( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

$total = $cart->cart_contents_total;

// Percentage discount (10%)
if( $total >= 200000 )
   $discount = $total * 0.1;
if( $total >= 350000 )
    $discount = $total * 0.15;
if( $total >= 500000 )
    $discount = $total * 0.20;
$cart->add_fee( __('discount', 'woocommerce'), -$discount );
}

标签: phpwordpresswoocommercehook-woocommercediscount

解决方案


您还应该为前两个条件添加上限。否则,您可能会陷入多个 if 条件。

例如 390K 大于 200K 并且也大于 350K。

add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_total',25, 1 );
function discount_based_on_total( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    $total = $cart->cart_contents_total;

    // Percentage discount (10%)
    if( $total >= 200000 && $total < 350000 ){
       $discount = $total * 0.1;
    }
    else if( $total >= 350000  && $total < 500000 ){
        $discount = $total * 0.15;
    }
    else if( $total >= 500000 ){
        $discount = $total * 0.20;
    }
    else{
        $discount = 0;
    }

    $cart->add_fee( __('discount', 'woocommerce'), -$discount );
}

推荐阅读