php - 从州代码中获取运输州的名称,或者如果用户在 WooCommerce 中键入它
问题描述
在我的情况下,我有以下代码显示州的名称,对于没有添加州的国家,(它仅在用户手动编写时显示文本)。
但是如果用户选择了一个添加了州的国家,那么它会显示代码而不是州名:`
<?php
$custom_order_meta = get_post_meta($order->get_order_number(), '_shipping_state', true);
if( ! empty($custom_order_meta) )
{ ?>
<p> <?php
printf( '<b>Region / Province:</b> ' . esc_html( '%s', 'woocommerce' ), esc_html($custom_order_meta) );?>
</p> <?php
}
?>
灵感来自Get state name 而不是 Woocommerce answer code 中的 code,它显示客户国家 state 的 name。但是当客户手动键入时,此 code 不处理。
当用户键入它和用户选择它时,我怎样才能让它在两种情况下都能正常工作?
解决方案
尝试以下操作(假设$order
变量被定义为当前WC_Order
对象):
<?php
$shipping_country = $order->get_shipping_country();
$shipping_state = $order->get_shipping_state();
if( ! empty($shipping_state) ) {
$country_states = WC()->countries->get_states( $shipping_country );
$value = isset($country_states[$shipping_state]) ? $country_states[$shipping_state] : $shipping_state;
if( ! empty($value) ) {
echo '<p><strong>' . __("Region / Province", "woocommerce") . '</strong>: ' . esc_html($value) . '</p>';
}
}
?>
测试和工作。
推荐阅读
- mongodb - 如何将 mongodb 的 Hash Id 替换为简单的 Int?
- django - 在 django 中登录没有 login() 功能的用户
- python - 如何使用python从响应中获取特定值
- javascript - 如何将下拉列表的值设置为我在 java 脚本中拥有的函数
- loops - 用句子中的元素循环一个字典
- amcharts - Amchart v4 数据未排序?(线路有奇怪的行为)
- jquery - 如何解决这个无休止滚动的代码?
- python - 为什么我不能将 True 存储在 Set 中?
- windows - TPM 消息充斥着我的事件查看器
- mysql - 别名续集