How to hide state field on WooCommerce checkout based on country

Viewed 556

Based on How to remove all Woocommerce checkout billing fields without errors answer code, this is my code attempt:

add_action( 'woocommerce_before_checkout_form', 'hide_checkout_billing_country', 5 );
function hide_checkout_billing_country() {
echo '<style>#billing_state_field{display:none !important;}</style>';
}
add_filter('woocommerce_billing_fields', 'customize_checkout_fields', 100 );
function customize_checkout_fields( $fields ) {
if ( is_checkout() ) {
// HERE set the required key fields below
$chosen_fields = array('first_name', 'last_name', 'address_1', 'address_2', 'city', 'postcode', 'country', 'state');
    foreach( $chosen_fields as $key ) {
        if( isset($fields['billing_'.$key]) && $key !== 'state') {
            unset($fields['billing_'.$key]); // Remove all define fields except country
        }
    }
}
return $fields;
}

My goal is to hide the state field depenging on country. Eg.

  • If country = Italy then the state field is shown
  • If country = France then state field is hidden..

So I tried to insert an if condition but without the desired result.

If someone could give me advice, it would be very appreciated.

1 Answers

Your code contains some errors and shortcomings

  • The modification in your code attempt, based on the state does not apply to the country
  • Your code contains an Fatal error: "Uncaught Error: call_user_func_array(): Argument #1 ($callback) must be a valid callback, function "customize_checkout_fields" not found or.. I've edited this though
  • You can use WC()->customer->get_billing_country() to get the billing country

So you get:

function filter_woocommerce_billing_fields( $fields ) { 
    // Returns true when viewing the checkout page
    if ( is_checkout() ) {
        // Get billing country
        $billing_country = WC()->customer->get_billing_country();
        
        // Multiple country codes can be added, separated by a comma
        $countries = array( 'IT' );
        
        // NOT in array
        if ( ! in_array( $billing_country, $countries ) ) {
            // HERE set the fields below, multiple fields can be added, separated by a comma
            $chosen_fields = array( 'state' );
            
            // Loop through
            foreach( $chosen_fields as $key ) {
                // Isset
                if ( isset( $fields['billing_' . $key] ) ) {
                    // Remove all defined fields
                    unset( $fields['billing_' . $key] );
                }
            }
        }
    }
    
    return $fields;
}
add_filter( 'woocommerce_billing_fields', 'filter_woocommerce_billing_fields', 10, 1 );
Related