I"m using the WooCommerce API to get the country list. I am doing:
$woo_countries = new WC_Countries();
$countries = $woo_countries->get_allowed_countries();
However, how does one get the state list for the default selected country? Also, when the user changes the country, does Woo have something built in that I can apply to the country field to update the states box or do I have to build that functionality myself?
Also, I know I can get the states for a country via doing:
$woo_countries->get_states(country_code);
...but I'm not sure how to get the default selected country to pass in to it?
I also know they have a combined country/state list you can load in but that's really messy and far too long for usability.
Try this , You still need to go for some javascript to make it work.I do not know if there is any way by default to make state drop-down list work as according to country drop-down list.I think it is helpful, give a try and let me know, if it worked.
so this makes your countries dropdown
and State dropdown
You need some javascript to make it work as you want. You may consider going through woocommerce_form_field .
I have added the below code on my functions.php and the screenshot shows what I am getting .Need to know about your checkout page to make it better.
"I believe it is all about creating the same HTML elements as in default checkout page."
HTML I am getting is somehow like( For country chosen United States(US) ):-
*New visitors Please consider going through edits,to know how this answer has been changed .
This is referred to as the "base country" by WooCommerce:
Read more in the API docs.
It should be noted that the default WooCommerce billing form template logic ensures that the default country and state are pre-selected. Here's what it looks like:
The third argument passed to
woocommerce_form_field()
ensures that the default country and state are pre-populated.