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

WooCommerce仅为阿联酋启用COD支付方式的自定义代码求助

WooCommerce 仅为阿联酋(UAE)启用货到付款(COD)支付方式的解决方案

前置确认

首先确保你已经在WooCommerce后台启用了货到付款(COD)支付方式:

  • 进入 WooCommerce > 设置 > 支付
  • 找到「货到付款」选项,勾选「启用」并保存设置

自定义代码实现

将以下代码添加到当前激活主题的 functions.php 文件中,或者使用自定义代码管理插件(如Code Snippets)来添加,避免主题更新导致代码丢失:

/**
 * 仅允许阿联酋地区用户看到货到付款(COD)支付方式
 */
add_filter( 'woocommerce_available_payment_gateways', 'restrict_cod_to_uae_only' );
function restrict_cod_to_uae_only( $available_gateways ) {
    // 后台不执行过滤逻辑
    if ( is_admin() ) return $available_gateways;

    // 获取用户的账单国家,为空则取配送国家
    $customer_country = WC()->customer->get_billing_country();
    if ( empty( $customer_country ) ) {
        $customer_country = WC()->customer->get_shipping_country();
    }

    // 阿联酋的ISO国家代码为AE
    $uae_code = 'AE';

    // 非阿联酋用户且COD网关存在时,移除COD选项
    if ( isset( $available_gateways['cod'] ) && $customer_country !== $uae_code ) {
        unset( $available_gateways['cod'] );
    }

    return $available_gateways;
}

关键说明

  1. 代码通过 woocommerce_available_payment_gateways 钩子过滤可用支付网关,只在前端生效,不影响后台设置。
  2. 优先读取用户的账单国家,若未填写则使用配送国家判断是否为阿联酋。
  3. 仅当用户地区为阿联酋时,保留COD支付选项;其他地区自动隐藏。

测试与排查

  • 切换结账页面的账单/配送国家为阿联酋,确认COD选项正常显示;切换至其他国家则隐藏。
  • 如果COD仍未显示,先检查后台是否已启用COD,再暂时禁用其他支付相关插件排查冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:53:13