How to Get WooCommerce States List

WooCommerce States ListIn a recent WooCommerce development project, I wanted to get all the countries and display the states and this required a creative way to create a quick solution. I created the solution I will share with you in this quick guide and also the WooCommerccode snippet that you can reuse in your WooCommerce development projects or customization of WooCommerce to help you save time and be more productive.

First, it is necessary we understand the methods we can use to get the countries in WooCommerce before we can check out the WooCommerce states list code. The following is the method that you use to get WooCommerce states list :

[php] // Get the states for a country.
WC_Countries::get_states($cc)

[/php]

You can also use the following code to get the countries by creating an object from the global WooCommerce object as in the code snippet below.

You can also pass the code of the country to the get_states() function and display the states for the specific country as shown in the image below where I have placed the US as the country in the get_states function:

[php] /**
* Action Hook to Display the countries list in WooCommerce in the header
*/

add_action(‘wp_head’, ‘njengah_header_example_code’);

function njengah_header_example_code(){

global $woocommerce;
$countries_obj = new WC_Countries();
$wc_states_list = $countries_obj->get_states( ‘US’ );

print(‘<pre>’);
print_r($wc_states_list);
print(‘</pre>’);

}

[/php]

When you add this code in the action hook and display it in the header to test it you can see that the countries are displayed as shown in the image below :

woocommerce get states list

Conclusion

In this post, we have looked at how you can get the states from the country object in WooCommerce and display them in the different locations in your WooCommerce theme or your WooCommerce store.

If you need further assistance with this issue, I can quickly check and advise what is the best way to get this done in your specific WooCommerce theme.  I would be glad to help you, feel free to reach out for further assistance, you can get in touch for a free consultation.

Similar Articles

  1. How to Add WooCommerce Registration Email Verification