June 4, 2019
Add a Required Checkbox Field In WooCommerce Checkout Page
This is how you add a checkbox to checkout in Woocommerce. The Checkbox will appear in the checkout and will not let the customer to proceed unless the checkbox is checked.
See also: How to add checkbox to checkout in woocommerce (not required)
See also: Add Multiple Required Checkbox Fields On WooCommerce Checkout Page
Add this code to your theme’s functions.php file:
// Add Checkbox add_action('woocommerce_after_checkout_billing_form', 'my_required_checkout_field'); function my_required_checkout_field() { woocommerce_form_field('age_confirm', array( 'type' => 'checkbox', 'class' => array('input-checkbox'), 'label' => __('I confirm that I am 21 years old or over.'), 'required' => true, ), WC()->checkout->get_value('age_confirm')); } // Process the checkout add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process'); function my_custom_checkout_field_process() { if (!$_POST['age_confirm']) { wc_add_notice(__('Please confirm you are 21 years old or over'), 'error'); } } //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 ($_POST['age_confirm']) { update_post_meta($order_id, 'Age Confirm', esc_attr($_POST['age_confirm'])); } }
This looks great, but when adding it to my website it doesn’t work and the whole website gives an error. Is this code still valid with the most recent woocommerce version?
Thank you,
Louise
Hi,
I just noticed it messed up for some reason and fixed the code in the post, can you try copying it again?
(Or replace the => with => in the code you used)
Thank you.
What do you mean by repalce => with => in the code?
The code is fixed now, no need to replace anything. copy, paste & modify texts. Good luck!
Hello there, I tried using your code and its working but i need to put two conditions. Can you please tell me how to achieve that? Also is it possible to store consents in database?
Hey
You mean that you need 2 required checkboxes?
And yes, it stores the consent in the DB.
Please check this guide: Add Multiple Required Checkbox Fields On WooCommerce Checkout Page