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

Viewed 789

In my case I have the following code that shows the name of the state, for countries that do not have added states, (it only shows the text when the user has written it manually).

But if the user has chosen a country that does have states added then it shows the code instead of the state name: `

<?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 
    }
    ?>

Inspired by Get state name instead of the code in Woocommerce answer code, which displays the name of the customer country state.But this code does not handle when customer types it manually.

How can I get it to work correctly in both cases, when user types it and when user selects it?

1 Answers

Try the following (assuming that $order variable is defined as the current WC_Order Object):

<?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>';
        }
    }
?>

Tested and works.

Related