Skip to content

Instantly share code, notes, and snippets.

@moonbyt3
Created December 16, 2023 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moonbyt3/82faae7f3e65fd2f72150821346eaee2 to your computer and use it in GitHub Desktop.
Save moonbyt3/82faae7f3e65fd2f72150821346eaee2 to your computer and use it in GitHub Desktop.
Add checkbox to WooCommerce checkout process
<?php
// This snippet will add a checkbox that a user needs to check before checkout.
// Triggers if a certain product belongs to a 'restricted' categroy.
add_action( 'woocommerce_review_order_before_submit', 'add_terms_and_conditions_checkbox' );
function add_terms_and_conditions_checkbox() {
$terms = array(
'restricted' => '<strong>' . __("I confirm I'm X years old", 'text-domain') . '</strong>', //Set checkbox text here
);
$displayed = array(); // keep track of which checkboxes have been displayed
// check if cart contains products from specified categories
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
$product_categories = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'slugs' ) );
foreach ( $terms as $category => $message ) {
if ( $category === 'restricted' && in_array( $category, $product_categories ) && !in_array( $category, $displayed ) ) {
// add terms and conditions checkbox
woocommerce_form_field( 'terms_'.$category, array(
'type' => 'checkbox',
'class' => array('form-row terms'),
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox'),
'required' => true,
'label' => $message,
));
$displayed[] = $category;
}
}
}
}
// Validate terms and conditions checkboxes
add_action( 'woocommerce_checkout_process', 'validate_terms_and_conditions_checkbox' );
function validate_terms_and_conditions_checkbox() {
$terms = array(
'restricted' => __("Please accept the terms and conditions for Online Courses", 'text-domain'), //Set error notice here
);
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
$product_categories = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'slugs' ) );
foreach ( $terms as $category => $error_message ) {
if ( $category === 'restricted' && in_array( $category, $product_categories ) && ! isset( $_POST['terms_'.$category] ) ) {
wc_add_notice( $error_message, 'error' );
}
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment