Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making woocommerce checkout form state field not required based on selected country

I have a WordPress+Woo-commerce site and I want to make the state field on the checkout form optional based on the selected country. For example I want my customers to add state field only if they belong to one of U.S.A. states.

How do I do this?

like image 563
Rituparna sonowal Avatar asked Dec 25 '22 07:12

Rituparna sonowal


2 Answers

In case someone stumbles on this, Woocommerce changed the name of the state fields. Below is the updated solution:

add_filter( 'woocommerce_checkout_fields','custom_override_default_address_fields' );

function custom_override_default_address_fields($fields){
    global $woocommerce;
    $country = $woocommerce->customer->get_country();

    if($country !== 'US'){
        $fields['billing']['billing_state']['required'] = false;
        $fields['shipping']['shipping_state']['required'] = false;
    }

    return $fields;
}
like image 70
Joel Parker Avatar answered Jan 13 '23 19:01

Joel Parker


Try this (in your functions.php)

add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );
function custom_override_default_address_fields( $address_fields ) {
     global $woocommerce;
     $country = $woocommerce->customer->get_country();
     if($country !== 'US'){
        $address_fields['state']['required'] = false;
     }
     return $address_fields;
}

This will make the 'state' field optional when the visitor is not from USA.
Hope this helps.

UPDATE

add_filter( 'woocommerce_checkout_fields', 'custom_override_default_address_fields' );
function custom_override_default_address_fields($fields){
    global $woocommerce;
    $country = $woocommerce->customer->get_country();
    if($country !== 'US'){
        $fields['billing']['state']['required'] = false;
        $fields['shipping']['state']['required'] = false;
    }
    return $fields;
}
like image 40
zipkundan Avatar answered Jan 13 '23 21:01

zipkundan