eylul
eylul

Reputation: 101

Get state name instead of the code in Woocommerce

I have added a custom list of states to my woocommerce using the code here: https://docs.woocommerce.com/document/addmodify-states/

The newly added states load fine on frontend and some backend screens, however in e-mails and user account screen, woocommerce only loads the the code / value instead of the actual name. (XX1, XX2 etc.)

I believe I can fix it using this logic:

echo WC()->countries->states[$current_user->billing_country][$current_user->billing_state]; //to get State name by state code

So I was wondering if it's possible to use this logic to create a function that would print the state name whenever the template calls the code? Any help would be very much appreciated.

Upvotes: 1

Views: 11467

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254378

You can use the following from the current user (WP_User object) to get the state label name:

$user = wp_get_current_user(); // The current user

$country = $user->billing_country;
$state = $user->billing_state;
echo WC()->countries->get_states( $country )[$state];

Tested and works


And for an order from the Order ID:

$order = wc_get_order($order_id); // The WC_Order object

$country = $order->get_billing_country();
$state = $order->get_billing_state();
echo WC()->countries->get_states( $country )[$state];

Upvotes: 8

Related Questions