从州代码获取发货州的名称,或者如果用户在 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 

    }

    ?>

受到获取州名称而不是 Woocommerce 应答代码中的代码的启发,该代码显示客户国家/地区州的名称。但是当客户手动键入时,此代码不会处理。


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


慕森王
浏览 72回答 1
1回答

江户川乱折腾

尝试以下操作(假设$order变量被定义为当前WC_Order对象):<?php&nbsp; &nbsp; $shipping_country = $order->get_shipping_country();&nbsp; &nbsp; $shipping_state&nbsp; &nbsp;= $order->get_shipping_state();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if( ! empty($shipping_state) ) {&nbsp; &nbsp; &nbsp; &nbsp; $country_states&nbsp; &nbsp;= WC()->countries->get_states( $shipping_country );&nbsp; &nbsp; &nbsp; &nbsp; $value = isset($country_states[$shipping_state]) ? $country_states[$shipping_state] : $shipping_state;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if( ! empty($value) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo '<p><strong>' . __("Region / Province", "woocommerce") . '</strong>: ' . esc_html($value) . '</p>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }?>经过测试并有效。
打开App,查看更多内容
随时随地看视频慕课网APP