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

WooCommerce添加后台产品复选框禁用COD支付网关代码不生效求助

WooCommerce 自定义复选框禁用COD支付网关修复方案

问题根源

你当前的代码逻辑混淆了产品类型和产品自定义复选框字段:

  • 你通过product_type_options钩子添加的只是产品编辑页的额外复选框配置,并没有注册名为doarcard的自定义产品类型,所以$product->is_type('doarcard')判断必然失效
  • simple是WooCommerce原生内置的产品类型,所以判断可以正常生效
  • 你的需求已经调整为按复选框取值判断,无需注册自定义产品类型,直接读取对应元字段值即可

核心修改点

仅需要修改woocommerce_available_payment_gateways过滤函数中的判断逻辑:

  • 将产品类型判断替换为读取_doarcard自定义字段值判断
  • 兼容可变产品的变体场景,避免子产品配置未生效的问题
  • 增加提前跳出逻辑,优化遍历性能

完整可运行代码

// 产品编辑页新增Doar Card复选框
add_filter("product_type_options", function ($product_type_options) {
    $product_type_options['doarcard'] = array(
        'id' => '_doarcard',
        'wrapper_class' => 'show_if_simple show_if_variable',
        'label' => __( 'Doar Card', 'woodmart' ),
        'description' => __( 'Activare doar plata cu card sau transfer bancar', 'woodmart' ), 
        'default' => 'no'
    );
    return $product_type_options;
});

// 保存复选框配置
add_action("save_post_product", function ($post_ID, $product, $update) {
    update_post_meta(
        $product->ID,
        "_doarcard",
        isset($_POST["_doarcard"]) ? "yes" : "no"
    );
}, 10, 3);

// 按复选框配置禁用COD支付网关
add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
function conditional_payment_gateways( $available_gateways ) {
    // 后台/空购物车场景直接返回
    if( is_admin() || empty(WC()->cart) ) 
        return $available_gateways;

    $prod_doarcard = false;
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        // 优先取变体ID,兼容可变产品场景
        $product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
        $product = wc_get_product($product_id);
        if ($product && $product->get_meta('_doarcard') === 'yes') {
            $prod_doarcard = true;
            break; // 找到符合条件的产品直接跳出循环,优化性能
        }
    }

    if($prod_doarcard) {
        unset($available_gateways['cod']);
    }
    
    return $available_gateways;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:27:01