If you're building online store in WooCommerce, you'll notice that you can make some fields hidden or optional, but can't some fields do not have these options. A bit annoying, but fixable!
Today I'l show you reliable way to make State field optional, or hide it completely, without any additional plugins. Here's what you need to do.
In order to make State field optional, you need to add this code to your WordPress website:
add_filter( 'woocommerce_get_country_locale', function( $country_locale ) {
// Get every country WooCommerce knows about
$all_country_codes = array_keys( WC()->countries->get_countries() );
foreach ( $all_country_codes as $cc ) {
if ( ! isset( $country_locale[ $cc ] ) ) {
$country_locale[ $cc ] = [];
}
$country_locale[ $cc ]['state'] = array_merge( $country_locale[ $cc ]['state'] ?? [], [
'hidden' => false,
'required' => false,
] );
}
return $country_locale;
}, 999 );
Ideally you should add this code to your WordPress Child theme's functions.php file. Depending on WordPress version you can find it in Appearance >> Theme File Editor or Tools >> Theme File Editor. Look for file functions.php on the right, and add this code to the end of the file.
If you want to hide or completely remove field State from Checkout block, the code is basically identical:
add_filter( 'woocommerce_get_country_locale', function( $country_locale ) {
// Get every country WooCommerce knows about
$all_country_codes = array_keys( WC()->countries->get_countries() );
foreach ( $all_country_codes as $cc ) {
if ( ! isset( $country_locale[ $cc ] ) ) {
$country_locale[ $cc ] = [];
}
$country_locale[ $cc ]['state'] = array_merge( $country_locale[ $cc ]['state'] ?? [], [
'hidden' => true,
'required' => false,
] );
}
return $country_locale;
}, 999 );
The only difference between this code and the one above is line "' hidden' => true, ". Now the field won't show up in checkout page.
Personally I'm not the biggest fan of installing plugins for every single modification. Site might become too hard to maintain. But if you really want to achieve the same result with plugin, the one I recommend is Checkout Field Editor (Checkout Manager) for WooCommerce by ThemeHigh. It can have controls for both Classic checkout and Block-based checkout.