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

请求协助创建WooCommerce折扣规则:满4件享最低价商品5折

WooCommerce实现“满4件享最低价商品50%折扣”规则

实现代码

将以下代码添加到你的WordPress主题functions.php文件末尾,或者自定义功能插件中:

add_action('woocommerce_cart_calculate_fees', 'apply_lowest_item_half_discount', 10, 1);
function apply_lowest_item_half_discount($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;

    // 检查购物车商品总数是否≥4
    if ($cart->get_cart_contents_count() < 4) return;

    $lowest_unit_price = PHP_INT_MAX;
    $lowest_item_total = 0;

    // 遍历购物车商品,筛选单价最低的商品小计
    foreach ($cart->get_cart() as $item) {
        $unit_price = $item['data']->get_price();
        $item_total = $item['line_subtotal'];
        
        if ($unit_price < $lowest_unit_price) {
            $lowest_unit_price = $unit_price;
            $lowest_item_total = $item_total;
        }
    }

    // 计算50%折扣金额并添加到购物车
    $discount = $lowest_item_total * 0.5;
    if ($discount > 0) {
        $cart->add_fee(__('最低价商品50%折扣', 'woocommerce'), -$discount);
    }
}

代码说明

  • 借助woocommerce_cart_calculate_fees钩子,在购物车计算费用时实时触发折扣逻辑
  • 先校验购物车商品数量,不足4件时直接跳过折扣计算
  • 遍历所有商品,定位单价最低的商品,以该商品的小计金额为基数计算50%折扣
  • 通过添加负向费用的方式实现折扣,折扣会清晰显示在购物车和结算页面的费用明细区域

自定义扩展(可选)

如果需要排除特定商品或分类,可在遍历商品时增加判断逻辑:

// 示例:排除ID为123的商品和slug为"gift-card"的商品分类
if ($item['product_id'] == 123 || has_term('gift-card', 'product_cat', $item['product_id'])) {
    continue;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:35:08