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

WooCommerce购物车含指定商品时按品类设置289€封顶折扣实现求助

实现方案

前置配置

  • 先在WooCommerce后台查询灯光塑形工具类的产品分类Slug,下文示例中以lighting-shaping-tools指代,替换为你实际的分类标识即可
  • 后台原有的promob10优惠券调整设置:类型选择固定购物车折扣,金额随意填写即可,后续会通过代码动态覆盖实际折扣值

完整可使用代码

// 自动应用/移除B10 Plus专属优惠
add_action( 'woocommerce_before_cart', 'auto_apply_b10_coupon' );
add_action( 'woocommerce_before_checkout_form', 'auto_apply_b10_coupon' );
function auto_apply_b10_coupon() {
    $coupon_code = 'promob10';
    $b10_plus_product_ids = array( 373 ); // 可替换为实际B10 Plus产品ID
    $has_b10 = false;

    // 遍历购物车判断是否有B10 Plus
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( in_array( $cart_item['product_id'], $b10_plus_product_ids ) ) {
            $has_b10 = true;
            break;
        }
    }

    // 有B10 Plus且未应用优惠券则添加
    if ( $has_b10 && ! WC()->cart->has_discount( $coupon_code ) ) {
        WC()->cart->apply_coupon( $coupon_code );
        wc_print_notices();
    }
    // 无B10 Plus但已应用优惠券则移除
    elseif ( ! $has_b10 && WC()->cart->has_discount( $coupon_code ) ) {
        WC()->cart->remove_coupon( $coupon_code );
        wc_clear_notices();
        wc_add_notice( 'B10 Plus已移除,对应优惠已取消', 'notice' );
    }
}

// 动态计算promob10优惠券的实际折扣金额
add_filter( 'woocommerce_coupon_get_amount', 'custom_b10_coupon_amount', 10, 2 );
function custom_b10_coupon_amount( $amount, $coupon ) {
    // 只处理promob10优惠券
    if ( $coupon->get_code() !== 'promob10' ) {
        return $amount;
    }

    $lighting_category_slug = 'lighting-shaping-tools'; // 替换为实际灯光塑形工具类的分类Slug
    $max_discount = 289; // 最高减免金额,可调整
    $category_subtotal = 0;

    // 遍历购物车计算指定分类商品的小计总和
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( has_term( $lighting_category_slug, 'product_cat', $cart_item['product_id'] ) ) {
            $category_subtotal += $cart_item['line_subtotal']; // line_subtotal为税前小计,要税后的话改成line_total
        }
    }

    // 折扣取品类小计和最高减免额的最小值
    return min( $category_subtotal, $max_discount );
}

逻辑说明

  • 自动判断购物车是否存在B10 Plus产品,存在则自动应用promob10优惠券,不存在则自动移除该优惠券避免误优惠
  • 动态计算所有灯光塑形工具类商品的购物车小计,可根据需求切换税前/税后计算逻辑
  • 实际折扣金额取「品类小计」和「289欧元」的最小值,完全匹配需求:品类小计≤289€时全额减免,>289€时最多减免289€

测试建议

测试时请清空WooCommerce缓存,覆盖以下场景验证:

  • 购物车无B10 Plus时,灯光塑形工具类商品无折扣
  • 购物车有B10 Plus、灯光塑形类商品小计100€时,减免100€
  • 购物车有B10 Plus、灯光塑形类商品小计300€时,仅减免289€
  • 从购物车移除B10 Plus后,对应优惠自动失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:15:02