Make Billing and Shipping Fields Optional and required in WooCommerce.

How to Make Billing and Shipping Fields Optional and required in WooCommerce?

Make Billing and Shipping Fields Optional and required in WooCommerce

 
For not required
  1. country
  2. first_name
  3. last_name
  4. company
  5. address_1
  6. address_2
  7. city
  8. state
  9. postcode
add_filter( 'woocommerce_default_address_fields' , 'optional_default_address_fields' );
 function optional_default_address_fields( $address_fields ) {
 $address_fields['company']['required'] = false;
 $address_fields['postcode']['required'] = false;
 $address_fields['city']['required'] = false;
 $address_fields['state']['required'] = false;
 return $address_fields;
 }
For required
add_filter( 'woocommerce_default_address_fields' , 'optional_default_address_fields' );
 function optional_default_address_fields( $address_fields ) {
 $address_fields['company']['required'] = true;
 $address_fields['postcode']['required'] = true;
 $address_fields['city']['required'] = true;
 $address_fields['state']['required'] = true;
 return $address_fields;
 }

Make Billing and Shipping Fields Optional and required in WooCommerce

t looks like all of the WooCommerce checkout fields are added in the billing form template but I’m not sure where they’re coming from. Is there an easy way to change which of these fields are required? I don’t need the phone, but I do need the company field instead and I’m not seeing where the fields are.


The WooCommerce checkout fields are generated outside of the checkout template, so we have to do a bit of digging to find them. At the top of the billing form template, we notice that we’re using the $checkout global: @global WC_Checkout $checkout

This tells us we need to look at the WC_Checkout class to find where these fields are being generated instead, and we’ll go down a tiny rabbit hole 🙂 .

The checkout class defines the checkout fields for billing and shipping, and it pulls them from WC()->countries->get_address_fields. This means we have to dig down one more level, and go to /includes/class-wc-countries.php. As these fields may change by country or state / province, they’re generated here when we check the country, and then the checkout template outputs the right fields in the right order for the selected country.

The first thing I’m going to do is find the “company” field. I do a bit of searching, and find that it’s generated by get_default_address_fields, and can be modified by the woocommerce_default_address_fields filter, which passes in all of these fields.

Click here to get more information

Read More Posts

Leave a Reply

Your email address will not be published. Required fields are marked *