2

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?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Williams
  • 421
  • 4
  • 18

1 Answers1

3

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • the code generates an error: Syntax error, unexpected ':' – Williams Aug 19 '20 at 15:27
  • @Williams Sorry my fault, a stupid mistake. Updated tested and works. – LoicTheAztec Aug 19 '20 at 17:18
  • It works very well, thank you very much, now I need to apply it to: get_user_meta (get_current_user_id () to be able to implement it in the my-address.php template can you help me or should I ask another question? – Williams Aug 20 '20 at 12:47
  • @Williams Better ask another question, as the rule on StackOverFlow is one question at the time. – LoicTheAztec Aug 20 '20 at 12:49