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; } 2 Answers
Answers 1
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 stateMandatory ($billingstate) {   if ($billingstate== "") {     wc_add_notice("State field is mandatory", "error");   }   return $order; } add_filter( 'woocommerce_create_order', 'stateMandatory', 10, 1 ); Answers 2
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; }  
0 comments:
Post a Comment