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

如何为多款特定商品隐藏WooCommerce购物车及结账页优惠券字段?

修改WooCommerce代码支持多款商品隐藏优惠券字段

你可以通过以下方式修改代码,实现多款商品在购物车和结账页面隐藏优惠券字段:

修改后的完整代码

// 在购物车和结账页面,若购物车包含指定商品则隐藏优惠券字段
function disable_coupon_for_restricted_products( $enabled ) {
    // 检查是否在购物车或结账页面
    if ( is_cart() || is_checkout() ) {
        // 在这里添加需要隐藏优惠券的商品ID,用逗号分隔
        $restricted_product_ids = array(240790, 12345, 67890);
        $in_cart = false;
        
        foreach( WC()->cart->get_cart() as $cart_item ) {
            $product_in_cart = $cart_item['product_id'];
            // 检查当前商品是否在限制列表中
            if ( in_array( $product_in_cart, $restricted_product_ids ) ) {
                $in_cart = true;
                break; // 找到匹配项后直接跳出循环,提升效率
            }
        }

        if ( $in_cart ) {
            $enabled = false;
        }
    }
    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_for_restricted_products' );

关键修改说明

  • 合并重复函数:原代码分别处理购物车和结账页面的两个函数逻辑完全一致,合并为一个函数后减少冗余,更易维护。
  • 使用数组存储商品ID:将单个商品ID改为数组$restricted_product_ids,你可以直接在数组中添加多个商品ID(如示例中的12345、67890),满足多款商品的需求。
  • 优化判断逻辑:用in_array()替代原有的单个ID对比,代码更简洁;找到匹配商品后直接跳出循环,提升代码执行效率。
  • 同时适配两个页面:通过is_cart() || is_checkout()同时判断购物车和结账页面,无需分开处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:05:03