Step 1: Add the Checkbox
Firstly, you need to add the checkbox. To do that,

Go to your WordPress Dashboard
Select Appearance > Theme file editor
Find your functions.php and add the following code to it;
Here is the function for adding the checkbox:

function cw_custom_checkbox_fields( $checkout ) {

echo ‘

‘ . esc_html__( ‘Separation Heading:’, ‘your-text-domain’ ) . ‘

‘;

woocommerce_form_field( ‘custom_checkbox’, array(

‘type’ => ‘checkbox’,

‘label’ => esc_html__( ‘Aggregation Policy’, ‘your-text-domain’ ),

‘required’ => true,

), $checkout->get_value( ‘custom_checkbox’ ));

}
Here is the hook for adding the checkbox:

add_action(‘woocommerce_after_order_notes’, ‘cw_custom_checkbox_fields’);
Step 2: Set the Condition to ‘Required’
Now, you need to set the conditions for the field. For that, the field must be set to required.

So, if a user leaves this field empty, an error message will 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 checkbox has been added to the WooCommerce checkout page.

output
Step 3: Save the Customer Data
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’]));
}
And that’s it. You’re done.

By admin