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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With