You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带指定product-tag的WooCommerce商品多档批量动态定价问题咨询

问题原因

你的代码无法触发更高档位折扣的核心原因是条件判断顺序倒置:你将门槛更低的$threshold1放在了判断逻辑的最前方,只要购物车内符合标签的商品数量≥2,就会命中第一个if分支,后续的elseif分支永远不会被执行。同时原有写法扩展性差,新增档位需要重复编写大量冗余代码。

优化后代码

下面是支持任意多档位配置的修复版代码,后续新增档位仅需修改折扣规则数组即可:

function bbloomer_quantity_based_pricing( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    // 统计符合指定标签的商品总数量
    $tag_total_count = 0;
    $target_tag = 'petit-format';

    foreach ( $cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        if( has_term( $target_tag, 'product_tag', $product_id ) ) {
            $tag_total_count += $cart_item['quantity'];
        }
    }

    // 折扣规则配置:门槛从高到低排序,新增档位直接往数组最前面加即可
    $discount_rules = [
        ['threshold' => 100, 'discount' => 0.607143],
        ['threshold' => 50, 'discount' => 0.607143],
        ['threshold' => 20, 'discount' => 0.571429],
        ['threshold' => 10, 'discount' => 0.5],
        ['threshold' => 6, 'discount' => 0.428571],
        ['threshold' => 3, 'discount' => 0.285714],
        ['threshold' => 2, 'discount' => 0.142857],
    ];

    // 匹配符合的最高档位折扣
    $matched_discount = 0;
    foreach ($discount_rules as $rule) {
        if ($tag_total_count >= $rule['threshold']) {
            $matched_discount = $rule['discount'];
            break;
        }
    }

    // 有匹配的折扣则更新对应商品价格
    if ($matched_discount > 0) {
        foreach ( $cart->get_cart() as $cart_item ) {
            $product_id = $cart_item['product_id'];
            if( has_term( $target_tag, 'product_tag', $product_id ) ) {
                $new_price = round( $cart_item['data']->get_price() * ( 1 - $matched_discount ), 2 );
                $cart_item['data']->set_price( $new_price );
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'bbloomer_quantity_based_pricing', 10, 1 );

使用说明

  • 后续需要新增折扣档位时,只需按照['threshold' => 数量门槛, 'discount' => 折扣比例]的格式,将新档位添加到$discount_rules数组的最顶部即可,无需修改其他逻辑
  • 代码会自动匹配用户符合的最高档位折扣,不会出现低档位优先触发的问题

内容的提问来源于stack exchange,提问作者Caroline

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:54:00