获取州名称而不是 Woocommerce 中的代码

eyl*_*lul 1 php country wordpress state woocommerce

我使用此处的代码向我的 woocommerce 添加了自定义状态列表: https: //docs.woocommerce.com/document/addmodify-states/

新添加的状态在前端和某些后端屏幕上加载良好,但是在电子邮件和用户帐户屏幕中,woocommerce 仅加载代码/值而不是实际名称。(XX1、XX2 等)

我相信我可以使用以下逻辑修复它:

echo WC()->countries->states[$current_user->billing_country][$current_user->billing_state]; //to get State name by state code
Run Code Online (Sandbox Code Playgroud)

所以我想知道是否可以使用此逻辑创建一个函数,每当模板调用代码时,该函数都会打印状态名称?任何帮助将非常感激。

Loi*_*tec 8

您可以使用当前用户WP_User对象)中的以下内容来获取状态标签名称

$user = wp_get_current_user(); // The current user

$country = $user->billing_country;
$state = $user->billing_state;
echo WC()->countries->get_states( $country )[$state];
Run Code Online (Sandbox Code Playgroud)

经过测试并有效


对于来自订单 ID 的订单:

$order = wc_get_order($order_id); // The WC_Order object

$country = $order->get_billing_country();
$state = $order->get_billing_state();
echo WC()->countries->get_states( $country )[$state];
Run Code Online (Sandbox Code Playgroud)