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

修复WooCommerce按用户角色对指定分类满量打折的适用范围问题

WooCommerce 分类专属折扣代码修复

问题原因

原有代码在满足折扣门槛后,直接读取购物车全部商品的总金额计算折扣,导致非目标分类的商品也被纳入折扣计算范围。

修复后代码

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

    // 仅对 'company' 用户角色生效
    if ( ! current_user_can( 'company' ) )
        return;

    // 目标分类
    $category = 'categorie-1';

    // 折扣比例
    $percentage = 50; // 50%

    // 最低购买数量门槛
    $minimun_quantity = 25;

    // 初始化变量:目标分类商品总数量、目标分类商品总金额
    $current_quantity = 0;
    $category_subtotal = 0;

    // 遍历购物车所有商品
    foreach ( $cart->get_cart() as $cart_item ) {
        // 判断是否属于目标分类
        if ( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
            // 累加目标分类商品数量
            $current_quantity += $cart_item['quantity'];
            // 累加目标分类商品总金额(未计算折扣的原价小计)
            $category_subtotal += $cart_item['line_subtotal'];
        }
    }

    // 达到最低购买数量时应用折扣
    if ( $current_quantity >= $minimun_quantity ) {
        // 仅用目标分类的总金额计算折扣
        $discount = $category_subtotal * $percentage / 100;

        // 应用折扣
        $cart->add_fee( sprintf( __( '折扣 (%s)', 'woocommerce' ), $percentage . '%'), -$discount, true );     
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );

核心调整说明

  • 新增$category_subtotal变量,遍历购物车时仅累计categorie-1分类下的商品总金额
  • 折扣计算基数从全局购物车总金额替换为目标分类专属总金额,确保非目标分类商品不参与折扣计算
  • 原有角色校验、数量门槛规则完全保留,不影响原有业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:36:02