繁体   English   中英

从 state 代码或用户输入 WooCommerce 中获取运输名称 state

[英]Get the name of the shipping state from a state code or if user types it in WooCommerce

在我的例子中,我有以下代码显示 state 的名称,对于没有添加州的国家(它仅在用户手动编写时显示文本)。

但是,如果用户选择了一个添加了州的国家,那么它会显示代码而不是 state 名称:`

<?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 instead of the code in Woocommerce answer code,显示客户国家名称state。但是当客户手动输入时,此代码不处理。

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

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

测试和工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM