'Woocommerce Checkout - Add conditional field required if one field is filled
I want to add a conditional requirement on the Checkout page. Because a lot of people fill the Name of Company without they are a company. And I want to add to the "billing_company" field a conditional where if the customer fill the "billing_company" field need to be fill the "woocommerce_eu_vat_number" field too. The problem is those two fields are optionals. But I want to do them as required if billing_company /billing_vat_number is filled. Is it possible?
Field Codes in HTML:
<p class="form-row form-row-wide" id="billing_company_field" data-priority="30">
<label for="billing_company" class="">Company name <span class="optional">(optional)</span></label>
<span class="woocommerce-input-wrapper czr-focus">
<input type="text" class="input-text czr-focusable" name="billing_company" id="billing_company" placeholder="" value="" autocomplete="organization">
</span>
</p>
<p class="form-row form-row-wide" id="woocommerce_eu_vat_number_field" data-priority="120">
<label for="woocommerce_eu_vat_number" class="">VAT number (companies) <span class="optional">(optional)</span></label>
<span class="woocommerce-input-wrapper czr-focus">
<input type="text" class="input-text czr-focusable" name="billing_vat_number" id="woocommerce_eu_vat_number" placeholder="" value="">
</span>
</p>
I want a code something like this. Sorry because I can understand more or less php code but I don't know how to create it from zero. T_T
<?php
function custom_required_vat_billing_fields() {
if( !empty ('billing_company' ) {
set ($fields['billing']['billing_vat_number'] = class [REQUIRED=true] );)
} if not {
wc_add_notice(__('Please enter a VAT number if you are a company'), 'error');
}
};
return $fields;
}
add_filter('woocommerce_checkout_fields','custom_required_vat_billing_fields');
?>
Solution 1:[1]
If checkbox is checked, then field company ID is required. Write code below to your child themes functions.php file and change ID of elements: wi_as_company is ID of checkbox and billing_company_wi_id is ID of required field if checkbox is checked
add_action( 'woocommerce_checkout_process', 'afm_validation' );
function afm_validation() {
if ( isset($_POST['wi_as_company']) && isset($_POST['billing_company_wi_id']) && empty($_POST['billing_company_wi_id']) ) {
wc_add_notice( __("Please fill company ID"), "error" );
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jps |