Make company field required only in B2B dedicated forms

Snippets

Friday, 30 December 2022

WooCommerce B2B has the option “Registration forms” which allows you to add billing data to registration form.
When you use the specific shortcode [wcb2bloginform] that allow you to create a dedicated login / registration forms for B2B users, billing data are also added to this form.

In some particular scenarios (especially in hybrid B2C / B2B shops), based on your specific needs, you may need to differentiate the company field behavior (optional / mandatory) based on the customer type (B2C/B2B).

For example, if you want to make company field optional for B2C registration form (WooCommerce default registration page) but mandatory for B2B registration forms (WooCommerce B2B specific registration pages), edit functions.php file that you find in your site’s FTP space in:

 wp-content/themes/{YOUR_ACTIVE_THEME}/functions.php

and insert this code:

add_filter( 'wcb2b_register_form_fields', function( $fields ) {
    $fields['billing_company']['required'] = !is_account_page();
    return $fields;
} );

With this snippet, if registration form is generated by WooCommerce B2B shortcode (assumed B2B registration form), company field will be required, if registration form is generated by WooCommerce default shortcode (assumed B2C registration form), company field will be optional.

WARNING! Before making any changes, make sure you have made a complete backup of site files and database.
It is advisable not to edit the theme files directly, but to use a child theme.
For more information on child themes, please read: WordPress Official guide on Child Themes