Skip to content
Advertisement

How to make Woocommerce checkout field not required if checkbox is checked?

In WordPress Woocommerce checkout page I want to make field ‘billing_name’ not required if checkbox ‘buy_on_company’ is checked.

I have managed to hide ‘billing_name’ in checkout page, but how to make it not required also?

add_filter( 'woocommerce_checkout_fields' , 'company_checkbox_and_new_checkout_fields', 9999 );
  

function company_checkbox_and_new_checkout_fields( $fields ) {
    
$fields['billing']['buy_on_company'] = array( // CSS ID
    'type'      => 'checkbox',
    'label'     => __('Buy on company', 'woocommerce'),
    'class'     => array('form-row-wide'), // CSS Class
    //'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
    'clear'     => true,
    'priority'  => '10'
);   

    $fields['billing']['billing_name']['placeholder'] = 'First Name Last name';

return $fields;
}
function hook_javascript() {
  ?>
  <script>
        document.getElementById('buy_on_company').onclick = function () {
            if (this.checked) {
                document.getElementById('billing_name').style['display'] = 'none';
            } else {
                document.getElementById('billing_name').style['display'] = 'block';
            }

        };
  </script>
  <?php
}

add_action( 'woocommerce_after_checkout_form', 'hook_javascript' );

Advertisement

Answer

I have done this:

add_filter( 'woocommerce_checkout_fields' , 'company_checkbox_and_new_checkout_fields_1', 9999 );
function company_checkbox_and_new_checkout_fields_1( $fields ) {
        if (isset($_POST['buy_on_company'])) {          
            $fields['billing']['billing_name']['required'] = false;
            } else {
            $fields['billing']['billing_name']['required'] = true;  
        }
return $fields;
}

Now it doesn’t ask for billing name field.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement