user379888
user379888

Reputation:

Woocommerce require fields

Below is the code I am using to make states field mandatory for all places but for specific countries like Germany its still not mandatory. I want to make it mandatory for all.

add_filter( 'woocommerce_checkout_fields', 'custom_override_default_address_fields' );
function custom_override_default_address_fields($fields){
        $fields['billing']['state']['required'] = true;
        $fields['shipping']['state']['required'] = true;
    }
    return $fields;
}

Upvotes: 3

Views: 406

Answers (2)

user379888
user379888

Reputation:

I figured out WordPress itself removes the required state field in many countries (like Kuwait) and it can not be made required using,

   $fields['billing']['state']['required'] = true;
   $fields['shipping']['state']['required'] = true;

What I did is, I checked the size of of the input value in the state drop-down (when user presses order button) and if the value was empty, I showed an error.

function my_custom_checkout_field_process() {
    // You can make your own control here
    if ( ! $_POST[ 'billing_state' ] )
    {

        wc_add_notice( __('PLEASE SELECT A STATE' ), 'error' );
    }
}

Upvotes: 5

Juan Mellado
Juan Mellado

Reputation: 15113

Note that your code is incorrect, remove the extra '}'.

Use woocommerce_default_address_fields instead of woocommerce_checkout_fields:

add_filter('woocommerce_default_address_fields', 'custom_override_default_address_fields');

function custom_override_default_address_fields( $fields ) {
     $fields['state']['required'] = false;

     return $fields;
}

If you have other filters, try to add a priority (a priority of 20 will run after code with 10 priority):

add_filter('woocommerce_default_address_fields', 'custom_override_default_address_fields', 100);

And if you really need to use woocommerce_checkout_fields then use billing_stateand shipping_state instead of state:

add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');

function custom_override_checkout_fields( $fields ) {
  $fields['billing']['billing_state']['required'] = true;
  $fields['shipping']['shipping_state']['required'] = true;

  return $fields;
}

Upvotes: 2

Related Questions