Search code examples
phpwordpresswoocommercefieldcheckout

Make state checkout field required for a Vietnam country in WooCommerce


The country of Vietnam in WooCommerce does not have defined states, so I added some states to my checkout page.

This is my code:

add_filter( 'woocommerce_states', 'vietnam_cities_woocommerce' );
   function vietnam_cities_woocommerce( $states ) {
     $states['VN'] = array(
      'HCM' => __('Hồ Chí Minh', 'woocommerce') ,
      'HANOI' => __('Hà Nội', 'woocommerce') ,
      'HAIPHONG' => __('Hải Phòng', 'woocommerce') ,
           );
      return $states;
}

It do work as I would like, but it is an optional field for Vietnam.

How to make this state field as required for Vietnam?

Any help is appreciated.


Solution

  • The following function will make for Vietnam the state field as a required in woocommerce:

    add_filter( 'woocommerce_get_country_locale', 'custom_country_locale', 10, 1 );
    function custom_country_locale( $locale ) {
        $locale['VN']['state']['required'] = true;
    
        return $locale;
    }
    

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

    Explanations: Each country 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