I am struggling to set up a form with a default WooCommerce country and states selection dropdowns.
Basically, I want to show Country selection and then state selection based on the country selection. So if the user chooses UK, the new dropdown with states selection will show.
I got as far as this:
<?php
global $woocommerce;
$countries_obj = new WC_Countries();
$countries = $countries_obj->__get('countries');
$default_country = $countries_obj->get_base_country();
$default_county_states = $countries_obj->get_states( $default_country );
echo '<div id="ships_from_countries_field">' . __('Countries') . '';
woocommerce_form_field('my_country_field', array(
'type' => 'select',
'class' => array( 'chzn-drop' ),
'label' => __('Item ships from - country'),
'placeholder' => __('Select a Country'),
'options' => $countries
)
);
echo '</div>';
echo '<div id="ships_from_state_field">' . __('States') . '';
woocommerce_form_field('my_state_field', array(
'type' => 'select',
'class' => array( 'chzn-drop' ),
'label' => __('Item ships from - state'),
'placeholder' => __('Select a State'),
'options' => $default_county_states
)
);
echo '</div>';
?>
Countries dropdown is displaying countries and states dropdown displaying states of the shop base – UK
But how do I make them work together and save the values?
Cannot find any info, anybody has any experience making this work?
first of, there’s a type for country and state.. you don’t need to do much… it’s just like this…
take note of their type… they’re not of type select.
now on your problem..
PHP
you need to have localized script for country and state… I won’t go on how to use
wp_localize_script()
. Read the link if you need to. Here’s a part of it.javascript
with that, in your
my-js
script (a script file) you can read the state like this:you then have to add a change event on your country and repopulate state based on what country was selected…
example:
states["PH"]
if country selected is Philippinesyou can then build your options like this using jQuery..
I looked how woocommerce did it in checkout. Instead of making my own js I just included the js they already made and the included the data in the same format they use.