How to make (existing) billing fields conditional?
-
Hi,
I’m trying to figure out how to make some billing fields conditional. Basically I want to add a checkbox asking customer if he/she needs an invoice. Depanding on that choice I would like to make first and last name non mandatory (in case of invoice) and instead company name and VAT id fields mandatory.So when this checkbox is left blank everything stays as it is now, but when it’s checked – customer doesn’t need to fill in his personal data, rather the company info.
I found some tutorials on how to ADD new conditional fields but not a single one how to make conditional those which are already there.
I’ve tried this approach in my templates functions.php but it doesn’t work and I think it requires much deeper changes ??
function my_custom_checkout_field( $checkout ) { echo '<input type="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>'; woocommerce_form_field( 'my_field_name', array( 'type' => 'checkbox', 'class' => array('input-checkbox'), 'label' => __('Fill in this field'), 'placeholder' => __('Enter something'), ), $checkout->get_value( 'my_field_name' )); echo '</input>'; echo '<input type="submit" name="submit" value="Submit"></input>'; } add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process'); function my_custom_checkout_field_process() { // Check if set. if (isset($_POST['my_field_name'])) add_filter( 'woocommerce_billing_fields', 'wc_npr_filter_phone', 10, 1 ); function wc_npr_filter_phone( $address_fields ) { $address_fields['FIELDS TO MAKE COND.']['required'] = false; return $address_fields; } } /** * Update the order meta with field value */ add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' ); function my_custom_checkout_field_update_order_meta( $order_id ) { if ( ! empty( $_POST['my_field_name'] ) ) { update_post_meta( $order_id, 'My Field', sanitize_text_field( $_POST['my_field_name'] ) ); } }
- The topic ‘How to make (existing) billing fields conditional?’ is closed to new replies.