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

仅特定商品在购物车时移除WooCommerce结账条款与条件需求

WooCommerce仅全豁免商品购物车隐藏条款的修复方案

原代码的问题在于:只要购物车中存在目标商品(ID551)就隐藏条款,完全忽略了是否同时存在需要条款的门票商品,不符合你“混合购物车需保留条款”的需求。

以下是修正后的代码,支持添加多个豁免商品ID,严格实现仅当购物车全为豁免商品时隐藏条款的逻辑:

方案一:修改 checkout_fields 钩子(兼容原代码逻辑)

function hide_terms_for_exempt_products_only( $woocommerce_checkout_fields ) {
    // 定义无需同意条款的商品ID数组,可随时添加新ID
    $exempt_product_ids = array(551);

    if ( WC()->cart ) {
        $cart_items = WC()->cart->get_cart();
        $has_non_exempt_product = false;

        foreach ( $cart_items as $cart_item ) {
            // 检测是否有非豁免商品存在
            if ( !in_array( $cart_item['product_id'], $exempt_product_ids ) ) {
                $has_non_exempt_product = true;
                break;
            }
        }

        // 只有全是豁免商品时,才移除条款字段
        if ( !$has_non_exempt_product ) {
            unset( $woocommerce_checkout_fields['terms'] );
        }
    }

    return $woocommerce_checkout_fields;
}
add_filter( 'woocommerce_checkout_fields', 'hide_terms_for_exempt_products_only' );

方案二:使用专门的条款显示钩子(更推荐)

WooCommerce提供了woocommerce_checkout_show_terms钩子直接控制条款是否显示,逻辑更清晰:

function show_terms_only_for_non_exempt_products( $show_terms ) {
    // 豁免商品ID列表,可扩展
    $exempt_product_ids = array(551);

    if ( WC()->cart ) {
        $cart_items = WC()->cart->get_cart();
        $has_non_exempt_product = false;

        foreach ( $cart_items as $cart_item ) {
            if ( !in_array( $cart_item['product_id'], $exempt_product_ids ) ) {
                $has_non_exempt_product = true;
                break;
            }
        }

        // 存在非豁免商品则显示条款,否则隐藏
        $show_terms = $has_non_exempt_product;
    }

    return $show_terms;
}
add_filter( 'woocommerce_checkout_show_terms', 'show_terms_only_for_non_exempt_products' );

使用说明

  • 如需添加新的豁免商品(比如周边),直接在$exempt_product_ids数组中追加ID即可,例如:array(551, 666, 777)
  • 两个方案选其一即可,方案二更符合WooCommerce的钩子设计规范,优先推荐

内容的提问来源于stack exchange,提问作者hot ham water

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:00:25