X
    Categories: WooCommerce Tutorials, Tips and GuidesWordPress Tutorials, Tips and Guides

How to Create Checkbox Field In WooCommerce Checkout Page

Adding custom fields to the WooCommerce checkout page is a serious challenge. In many cases, this requires careful consideration it has serious implication for customers. In many cases, store owners use these additional fields to collect further data about the customers.

In this tutorial, I will highlight how you could add a custom field to the checkout field.

In this tutorial, remember that you would need to register the checkbox using a unique id woocommerce_after_order_notes. Once done, this custom field could be used after the order notes (as the name implies).

Add the Checkbox

Here is the function for adding the checkbox:

function cw_custom_checkbox_fields( $checkout ) {

    echo '<div class="cw_custom_class"><h3>'.__('Give Sepration Heading: ').'</h3>';

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',
        'label'         => __('Agreegation Policy.'),
        'required'  => true,
    ), $checkout->get_value( 'custom_checkbox' ));

    echo '</div>';
}

Here is the hook for adding the checkbox:

add_action('woocommerce_after_order_notes', 'cw_custom_checkbox_fields');

Save the Custom Data

Note that the field is set to required. Thus, if a user leaves this field empty, an error message should be generated. Since the error notification function add_error() has been depreciated, I will use wc_add_notive():

add_action('woocommerce_checkout_process', 'cw_custom_process_checkbox');

function cw_custom_process_checkbox() {
    global $woocommerce;

    if (!$_POST['custom_checkbox'])
        wc_add_notice( __( 'Notification message.' ), 'error' );
}

At this point, the custom field (checkbox has been added to the WooCommerce checkout page.

Remember that the information provided by the buyer through the custom field needs to be saved along with other data from the checkout page. Here is how the data from the checkbox will be saved with the other data:

add_action('woocommerce_checkout_update_order_meta', 'cw_checkout_order_meta');

function cw_checkout_order_meta( $order_id ) {
    if ($_POST['custom_checkbox']) update_post_meta( $order_id, 'checkbox name', esc_attr($_POST['custom_checkbox']));
}

Conclusion

In this tutorial, I have discussed the important issue of adding a custom field to the WooCommerce checkout page. To demonstrate the issue, I added a checkbox to the checkout page and then added validation and data saving portions.

If you need helped with the implementation of the idea on your WooCommerce store, do let me know through the comments section.

Owais Alam: is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at owais.alam@cloudways.com