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

WooCommerce供应商注册字段:如何将国家/州缩写转为全称显示?

解决WooCommerce后台用户编辑页国家/州显示缩写的问题

问题核心是WooCommerce默认存储国家和州的代码缩写(如PK、PK-21),后台用户编辑页默认直接输出存储值,未自动转换为全称。可以通过以下代码修改后台字段的显示逻辑,实现代码到全称的转换:

代码实现

将以下代码添加到你的主题functions.php文件或自定义插件中:

add_filter( 'woocommerce_admin_billing_fields', 'custom_admin_billing_display_full_country_state' );

function custom_admin_billing_display_full_country_state( $fields ) {
    // 转换国家代码为全称
    if ( isset( $fields['country'] ) ) {
        $fields['country']['display_callback'] = function( $user ) {
            $country_code = get_user_meta( $user->ID, 'billing_country', true );
            return $country_code && isset( WC()->countries->countries[ $country_code ] ) 
                ? WC()->countries->countries[ $country_code ] 
                : $country_code;
        };
    }

    // 转换州代码为全称(依赖对应国家的州数据)
    if ( isset( $fields['state'] ) ) {
        $fields['state']['display_callback'] = function( $user ) {
            $country_code = get_user_meta( $user->ID, 'billing_country', true );
            $state_code = get_user_meta( $user->ID, 'billing_state', true );
            
            if ( $state_code && $country_code ) {
                $states = WC()->countries->get_states( $country_code );
                return isset( $states[ $state_code ] ) ? $states[ $state_code ] : $state_code;
            }
            return $state_code;
        };
    }

    return $fields;
}

代码说明

  • 借助woocommerce_admin_billing_fields过滤器,修改后台账单地址字段的显示回调逻辑
  • 通过WC()->countries->countries匹配国家代码对应的全称
  • 通过WC()->countries->get_states( $country_code )获取对应国家的州数据,再匹配州代码得到全称
  • 若代码无对应全称(如自定义代码),会 fallback 显示原始代码,避免页面空白

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:57:09