Alessandro Valori
Alessandro Valori

Reputation: 49

How to hide state field on WooCommerce checkout based on country

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.

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

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

Upvotes: 2

Views: 1331

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29614

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 );

Upvotes: 2

Related Questions