Get country and state list by leverage WooCommerce data

WooCommerce is an e-commerce platform that offers a convenient and customizable way for businesses to sell their products online. One of its helpful features is the ability to set a customer’s country and state during the checkout process. This feature allows for accurate calculations of tax and shipping costs and ensures that orders are delivered to the correct location. Additionally, WooCommerce provides the flexibility to customize this feature or implement it on a custom page, making it a versatile option for businesses of all sizes.

To clarify, WooCommerce already has this functionality available on the checkout page where a user can select a country and the state list dynamically loads based on the country selection. However, if you would like to add this functionality to a custom page, we can explore how to do that. Let’s take a look.

First, you need to get all data in you page

PHP:
global $woocommerce;
$countries_obj   = new WC_Countries();
$countries   = $countries_obj->__get('countries');
$country_states = $countries_obj->get_states();
$state_json = wp_json_encode($country_states);

Remember to use wp_json_encode instead of PHP json_encode to get the json, WordPress has a lot of utility function for us.

Then we put all data into page

HTML Template:
<div class="col span_6 col_last">
    <?php
        woocommerce_form_field('country', array(
                'type'       => 'select',
                'class'      => array( 'cocreator-dropdown' ),
                'label'      => __('Country'),
                'placeholder'    => __('Enter something'),
                'options'    => $countries
            ),
            $country
        );
    ?>
</div>
<div class="col span_6 col_last">
    <div id="all_states" data-state='<?php echo wc_esc_json( wp_json_encode( $county_states ) ); ?>'>
    </div>
    <?php
        woocommerce_form_field('state', array(
                'type'       => 'select',
                'class'      => array( 'cocreator-dropdown' ),
                'label'      => __('State'),
                'placeholder'    => __('Enter something'),
                'options'    => [$state]
            ),
            $state,
        );
    ?>
</div>

Observe to the div has id all_states include data-state

Now we use JS to load dynamic data for state:

JS:
const all_states = $('#all_states').data('state');
const country_field = $('#country');
const state_field = $('#state');
state_field.attr('disabled', 'disabled');

country_field.on('change', function() {
    const countryKey = $(this).val();
    const stateObject = all_states[countryKey];
    if (stateObject && Object.keys(stateObject).length > 0) {
        var html_option = '';
        Object.keys(stateObject).forEach((item, i) => {
            html_option += `<option value="${item}">${stateObject[item]}</option>`;
        });
        state_field.append(html_option);
        state_field.removeAttr('disabled');
    } else {
        state_field.attr('disabled');
    }
})

Thank you so much for taking the time to read this blog post! Your support means a great deal to us, and we sincerely appreciate your interest in the topic. If you found this post helpful or informative, I would love to hear your thoughts on the matter. Feel free to leave a comment below with any feedback, questions, or suggestions you may have. Your comments and engagement help to create a community of learning and exploration, and it’s always a pleasure to hear from our readers.


At DelightInCode, we understand that building a website can seem like an intimidating task, especially if you’re new to the process. That’s why we offer our expertise and guidance throughout the entire process – from conception through launch. Our team of experienced professionals will work with you every step of the way, ensuring that your vision is realized in beautiful form and function.

So don’t hesitate – get in touch today if there’s anything at all we can do for you! With our help, launching a successful website has never been easier!

Leave A Reply