Sometimes, due to legal issues or terms of service, it is necessary to add a mandatory field on the checkout page so that customers agree and can place an order.
In this article we show you how to create an acknowledge field without the need to install plugins. The solution is divided into two parts:
- Add the field (html) in the checkout page.
- Validate that the field was marked to prevent the order from being processed.
Add the acknowledge field (html) in the checkout page.
The first part is simply to add the field(checkbox) right after the place order button. For this we use the action hook woocommerce_review_order_before_submit, the name of the kook is quite descriptive. We use this hook so that the client has the greatest visibility when trying to create the order.
//Action Hook to add content right before the place order button add_action( 'woocommerce_review_order_before_submit', 'wrt_add_checkout_checkbox', 10 ); function wrt_add_checkout_checkbox(){ woocommerce_form_field('wrt_acknowledge', array( 'type' => 'checkbox', 'label' => '<span>No return are allowed</span>', 'required' => true, 'class' => array('custom-class', 'custom-class-2'), 'label_class' => array('custom-label-class', 'custom-label-class-2'), 'input_class' => array('custom-input-class', 'custom-input-class-2'), )); }
In the hook callback a WooCommerce function (woocommerce_form_field) is defined, this function receives two parameters
$field_key: String that defines the key of the field.
$attributes: Array containing the attributes of the field.
Note: This function can be located in woocommerce/includes/wc-template-functions.php, check all the attribute you can use here
Validate that the field was checked to prevent the order from being processed.
//Check if the field was checked by the customer add_action( 'woocommerce_checkout_process', 'wrt_add_checkout_checkbox_warning'); function wrt_add_checkout_checkbox_warning(){ if(! (int) isset($_POST['wrt_acknowledge'])){ wc_add_notice('Please acknowledge the checkbox', 'error'); } }
The above code is very basic, it checks if the field was sent when the customer press the place order button. If the field was not checked then we show a notices.
Conclusions
As you can see, it is very easy to create a mandatory field and force the client to accept it, but the most important thing is that no plugin was used to achieve it. If you have the ability to write code, I advise you to always look for ways to implement custom solutions instead of filling your dashboard with dozens of plugins that ultimately slow down and make your site insecure.