Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RiaanKnoetze/f54ea539045e75b39be8b7a823596f5d to your computer and use it in GitHub Desktop.
Save RiaanKnoetze/f54ea539045e75b39be8b7a823596f5d to your computer and use it in GitHub Desktop.
A WooCommerce code snippet that forces the 'state' field to always display on checkout pages.
<?php
/**
* Modifies the billing address fields to make the state field required.
*
* @param array $address_fields The array of address fields used in WooCommerce checkout.
* @return array The modified array of address fields with 'state' field set as required.
*/
function force_state_field_default_required( $address_fields ) {
// Set the 'required' flag for the 'billing_state' field to true.
$address_fields['billing_state']['required'] = true;
// Return the modified address fields array.
return $address_fields;
}
// Add a filter to WooCommerce to apply the above function to the billing fields.
add_filter( 'woocommerce_billing_fields', 'force_state_field_default_required');
/**
* Modifies the locale settings to make the state field required for all countries.
*
* @param array $locale The array of country locales provided by WooCommerce.
* @return array The modified array of locales with 'state' field set as required for all countries.
*/
function force_state_field_locale_required( $locale ) {
// Access the global locales variable.
global $locales;
// Get all country codes from WooCommerce.
$country_codes = array_keys( WC()->countries->get_countries() );
// Initialize the locales array.
$locales = array();
// Loop through each country code.
foreach ( $country_codes as $country_code ) {
// Set the 'state' field to be required for the current country.
$locales[$country_code] = array(
'state' => array(
'required' => true
),
);
}
// Return the modified locales array.
return $locales;
}
// Add a filter to WooCommerce to apply the above function to the country locale settings.
add_filter( 'woocommerce_get_country_locale', 'force_state_field_locale_required');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment