General Solutions&FAQ

Print

How to edit Required WooCommerce Checkout fields

All checkout fields in Woocommerce are generated outside of the checkout template, let’s investigate this point a little bit. At the beginning of  billing form template$checkout global: @global WC_Checkout $checkoutis used. Therefore, we need to look at the WC_Checkout class to find where these fields are being generated instead. The checkout class defines the checkout fields for billing and shipping, and it pulls them from WC()->countries->get_address_fields. As a result, we need to go down one more level directory 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. First of all, find the “company” field. Couple actions and found out 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. Mentioned snippet should be added straight to child theme’s functions.php or custom plugin to adjust this:

function sv_require_wc_company_field( $fields ) { 
$fields['company']['required'] = true; 
return $fields; } 
add_filter( 'woocommerce_default_address_fields', 'sv_require_wc_company_field' );

Our company field became required. the other point is phone field. Let’s find where it’s generated. We can keep searching through the countries class, and find that get_address_fields will generate the email and phone fields, as these are specific to billing addresses. A filter is generated here that includes the form type so we can change both billing and shipping fields. We replace “type” with “billing_” to get a woocommerce_billing_fieldsfilter. This filter should be used for changing “required” from true to false for the billing phone Woocommerce Checkout field:

function sv_unrequire_wc_phone_field( $fields ) {
    $fields['billing_phone']['required'] = false;
    return $fields;
}
add_filter( 'woocommerce_billing_fields', 'sv_unrequire_wc_phone_field' );

Like previous one, this code should be located in child theme functions.php, otherwise, it will be erased after theme update. Both snippets are added, as a result, Company field became required, and the Phone field is no longer required.

Leave a Reply

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