首页 > 解决方案 > 从州代码中获取运输州的名称,或者如果用户在 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 不处理。

当用户键入它和用户选择它时,我怎样才能让它在两种情况下都能正常工作?

标签: phpwordpresswoocommercestatehook-woocommerce

解决方案


尝试以下操作(假设$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>';
        }
    }
?>

测试和工作。


推荐阅读