phpwordpresswoocommercecheckoutstates

Unset billing state checkout field for all countries except specific ones in Woocommerce


In Woocommerce, I am trying to unset the billing state field for all countries except specific ones on checkout page…

Here is my code:

add_filter( 'woocommerce_checkout_fields','custom_override_default_address_fields' );
function custom_override_default_address_fields($myfields){
  global $woocommerce;
  $country = $woocommerce->customer->get_billing_country();
  if($country !== 'US' || $country !== 'AU' || $country !== 'CA' || $country !== 'GB'){
    unset( $myfields['billing']['billing_state'] );
  }
  return $myfields;
}

But it doesn't work really…

How can I remove billing state field for all countries except specific ones in woocommerce?


Solution

  • It seems that you would like to remove billing state for all countries except for US, AU, CA and GB, so here is the way to do it, but it will affect billing and shipping state fields (both):

    add_filter( 'woocommerce_states' , 'keep_specific_country_states', 10, 1 );
    function keep_specific_country_states( $states ) {
        // HERE define the countries where you want to keep
        $countries = array('US', 'AU', 'CA', 'GB');
        $new_country_states = array();
    
        // Loop though all country states
        foreach( $states as $country_code => $country_states ){
            if( ! in_array( $country_code, $countries ) ){
                // Remove states from all countries except the defined ones
                $states[$country_code] = array();
            }
        }
        return $states;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and work.