How to add custom checkbox in WooCommerce checkout page without plugin

Recently I have found a code using that you can add required or non-required checkbox in checkout page without any plugin. I have personally used that code in the website and it works fine, so I thought I should share this with other people's. For this you need to add some code in theme functions.php file. Using that  code you can add a required checkbox field in the WooCommerce checkout page that forces a user to checkbox the request before they can proceed to payment, similar to the terms and condition checkbox.


Checkout-page-default


How to add the field:

Add the following code in your theme's functions.php file.


add_action( 'woocommerce_review_order_before_submit', 'wc_add_checkout_checkbox', 10 );

/**

 * Add WooCommerce additional Checkbox checkout field

 */

function wc_add_checkout_checkbox() {

   

    woocommerce_form_field( 'checkout_checkbox', array( // CSS ID

       'type'          => 'checkbox',

       'class'         => array('form-row mycheckbox'), // CSS Class

       'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),

       'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),

       'required'      => true, // Mandatory or Optional

       'label'         => 'Ok I agree with <a href="/checkout-checkbox" target="_blank" rel="noopener">Checkout Checkbox Page</a>', // Label and Link

    ));    

}


add_action( 'woocommerce_checkout_process', 'wc_add_checkout_checkbox_warning' );

/**

 * Alert if checkbox not checked

 */ 

function wc_add_checkout_checkbox_warning() {

    if ( ! (int) isset( $_POST['checkout_checkbox'] ) ) {

        wc_add_notice( __( 'Please acknowledge the Checkbox' ), 'error' );

    }

}


If you don't want a warning and leave the checkbox as optional remove the 2nd code block and change the required value in the 1st code block to false. 

After adding the above code in your functions.php file you will see additional checkbox field in checkout page. You can change the checkbox label and add the link on it according to your requirements. If you don't want to add any link then replace "label" option with following code:


 'label'  => 'Ok I agree with Checkout Checkbox Page', 


How's Checkout page will be display after adding that code:


Checkout Page woocommerce


That's it. If you have any question or query please leave the comment in comment box below. Thanks! Keep Coding!!!!

Post a Comment

0 Comments