I have a WordPress+Woo-commerce site and I want to make the state field on the checkout form optional based on the selected country. For example I want my customers to add state field only if they belong to one of U.S.A. states.
How do I do this?
I have a WordPress+Woo-commerce site and I want to make the state field on the checkout form optional based on the selected country. For example I want my customers to add state field only if they belong to one of U.S.A. states.
How do I do this?
add_filter( 'woocommerce_default_address_fields' , 'custom_override_state_required' );
function custom_override_state_required( $address_fields ) {
$wc = WC();
$country = $wc->customer->get_country();
if($country !== 'US'){
$address_fields['state']['required'] = false;
}
return $address_fields;
}
This is code that worked for me. I am posting this answer without editing @zipkundan answer because I don't see any mistakes in his answer but somehow it was not working for me. That may be because of WooCommerce version or may have another reason!! I recommend to try both answers if someone have similar requirements.
In case someone stumbles on this, Woocommerce changed the name of the state fields. Below is the updated solution:
add_filter( 'woocommerce_checkout_fields','custom_override_default_address_fields' );
function custom_override_default_address_fields($fields){
global $woocommerce;
$country = $woocommerce->customer->get_country();
if($country !== 'US'){
$fields['billing']['billing_state']['required'] = false;
$fields['shipping']['shipping_state']['required'] = false;
}
return $fields;
}
Try this (in your functions.php)
add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );
function custom_override_default_address_fields( $address_fields ) {
global $woocommerce;
$country = $woocommerce->customer->get_country();
if($country !== 'US'){
$address_fields['state']['required'] = false;
}
return $address_fields;
}
This will make the 'state' field optional when the visitor is not from USA.
Hope this helps.
UPDATE
add_filter( 'woocommerce_checkout_fields', 'custom_override_default_address_fields' );
function custom_override_default_address_fields($fields){
global $woocommerce;
$country = $woocommerce->customer->get_country();
if($country !== 'US'){
$fields['billing']['state']['required'] = false;
$fields['shipping']['state']['required'] = false;
}
return $fields;
}
I had trouble getting the other answers to work until I realized there's also the woocommerce_get_country_locale
hook from WC_Countries. Which sets state required based on the chosen country through javascript in the frontend.
add_filter('woocommerce_get_country_locale', 'update_country_locales', 10 , 1);
function update_country_locales($countries) {
foreach ($countries as $country => $fields) {
if (isset($fields['state']) && $country != 'US') {
$countries[$country]['state']['required'] = false;
}
}
return $countries;
}