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

WooCommerce中高价商品仅允许BACS支付的实现问题

问题描述

希望限制买家购买高价商品(价格超过99)时仅能通过BACS支付,编写的代码无法隐藏WooPayments信用卡/借记卡支付选项,不确定$available_gateways['card']是否是正确标识,求修正。

原代码(functions.php):

//////////// Restrict payment option to be BACS for high value items
add_filter('woocommerce_available_payment_gateways', 'restrict_bacs_for_high_value_items', 99, 1);
function restrict_bacs_for_high_value_items( $available_gateways ) {
    global $product;

    if ( is_admin() ) return $available_gateways; // Only on frontend

    $product_price = round($product->price);

    if ( isset($available_gateways['card']) && ($product_price > 99) ) {
        unset($available_gateways['card']);
    }
    return $available_gateways;
}
修正方案

问题1:支付网关标识错误

WooPayments的信用卡/借记卡支付网关标识不是card,正确标识是woocommerce_payments。

问题2:单个商品价格判断不合理

原代码只判断单个商品价格,但用户可能购买多个商品,应该用订单总金额作为判断依据,而非单个商品价格。

问题3:商品价格获取方式过时

$product->price是WooCommerce旧版写法,新版应使用$product->get_price()方法,且全局$product在结算页/购物车页无法准确获取所有商品信息,需改用订单总金额获取逻辑。

修正后的代码

//////////// Restrict payment option to be BACS for high value orders
add_filter('woocommerce_available_payment_gateways', 'restrict_bacs_for_high_value_orders', 99, 1);
function restrict_bacs_for_high_value_orders( $available_gateways ) {
    // 后台直接返回,不处理
    if ( is_admin() ) return $available_gateways;

    // 获取订单总金额(包含运费、税费等)
    $order_total = WC()->cart->total;

    // 判断总金额是否超过99,且WooPayments网关存在
    if ( isset($available_gateways['woocommerce_payments']) && $order_total > 99 ) {
        unset($available_gateways['woocommerce_payments']);
    }

    // 可选:强制保留BACS网关(如果需要确保BACS始终显示)
    if ( !isset($available_gateways['bacs']) && $order_total > 99 ) {
        $available_gateways['bacs'] = WC()->payment_gateways()->payment_gateways()['bacs'];
    }

    return $available_gateways;
}

额外说明

如果需要仅针对单个商品(而非订单总金额)判断,可修改逻辑遍历购物车商品:

// 遍历购物车所有商品,判断是否有单个商品价格超过99
$has_high_value_product = false;
foreach ( WC()->cart->get_cart() as $cart_item ) {
    $product = $cart_item['data'];
    if ( $product->get_price() > 99 ) {
        $has_high_value_product = true;
        break;
    }
}

if ( isset($available_gateways['woocommerce_payments']) && $has_high_value_product ) {
    unset($available_gateways['woocommerce_payments']);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:50:10