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

WooCommerce按用户角色实现指定分类满量折扣的代码调整咨询

调整后的实现代码
// 订阅用户购买指定分类商品满量享受折扣
add_action( 'woocommerce_cart_calculate_fees', 'subscriber_category_quantity_discount', 20, 1 );
function subscriber_category_quantity_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // 仅对订阅者角色生效
    if ( ! current_user_can('subscriber') )
        return;

    // === 可配置参数开始 ===
    $target_categories = array( 'clothes', 'shoes' ); // 填入指定商品分类的别名或ID,支持多个
    $required_quantity = 25; // 达标所需商品数量
    $discount_percent = 50; // 折扣百分比
    // === 可配置参数结束 ===

    $category_total_qty = 0;
    $category_total_amount = 0;

    // 遍历购物车统计指定分类商品的数量和总额
    foreach ( $cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        if ( has_term( $target_categories, 'product_cat', $product_id ) ) {
            $category_total_qty += $cart_item['quantity'];
            $category_total_amount += $cart_item['line_subtotal'];
        }
    }

    // 数量达标则应用折扣
    if ( $category_total_qty >= $required_quantity ) {
        $discount = $category_total_amount * $discount_percent / 100;
        $cart->add_fee( sprintf( __("指定分类折扣 (%s)", "woocommerce"), $discount_percent . '%'), -$discount, true );
    }
}
配置说明
  • $target_categories:替换为你需要指定的商品分类,支持填分类别名(如示例中的clothes)或分类数字ID,多个分类用英文逗号分隔即可
  • $required_quantity:可修改为你需要的达标数量,当前默认25件
  • $discount_percent:可修改折扣比例,当前默认50%
  • 本代码默认仅对指定分类的商品总额计算折扣,不会影响其他分类商品的价格;如果需要满量后全场商品都享受折扣,只需把计算折扣的$category_total_amount替换为$cart->get_subtotal()即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:24:07