Add state field for Portugal and make it required in WooCommerce Checkout

140 Views Asked by At

I am building my WooCommerce store and need to alter the checkout billing/shipping fields. Currently, it displays the state/county as optional for Portugal country, but it is important for me that it is required and marked with the red asterisk because this affects prices.

I have tried plugins like Checkout Field Editor for WooCommerce and others, but I have had no success. Have also tried some code I found online which I added to functions.php on child theme:

add_filter( 'woocommerce_billing_fields', 'ts_require_wc_state_field');
function ts_require_wc_state_field( $fields ) {
    $fields['billing_state']['required'] = true;
    return $fields;
}

and

add_filter( 'woocommerce_default_address_fields', 'custom_override_default_address_fields');
function custom_override_default_address_fields( $address_fields ) 
{
    $address_fields['billing_state']['required'] = true;
    return $address_fields;
}

Both code snippets didn't work.

Perhaps someone can help me out with the right code for child theme?

A bit of a novice at this, so any help is really appreciated.

1

There are 1 best solutions below

0
LoicTheAztec On

For some countries, like Portugal, it requires something different to work. Try the following:

add_filter( 'woocommerce_get_country_locale', 'change_portugal_country_locale', 100 );
function change_portugal_country_locale( $locale ) {
    $locale['PT']['state'] = array(
        'required' => true,
        'hidden'   => false,
        'priority' => 93, // state field after the postcode field
    );
    $locale['PT']['country'] = array(
        'priority' => 96, // country field after the state field
    );
    return $locale;
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works with the code below.

But as states are not defined in WooCommerce for Portugal, It will require you to define each state name (with its related state code) in the following function:

add_filter( 'woocommerce_states', 'potugal_states_woocommerce' );
function potugal_states_woocommerce( $states ) {
    $states['PT'] = array(
        'AAB' => __('State one aab', 'woocommerce') ,
        'BBC' => __('State two bbc', 'woocommerce') ,
        'CCD' => __('State three ccd', 'woocommerce') ,
    );
    return $states;
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

You will get something like:

enter image description here

and:

enter image description here

Explanations: Some countries have specific "locale" fields settings in WooCommerce. We are adding/altering the default WooCommerce country locale settings that are defined on WC_Countries get_country_locale() method

Related: Make state checkout field required for a Vietnam country in WooCommerce