Extra Agreement Checkbox for Certain Products
Adds a required checkbox to the checkout only when the cart has products from a chosen category, for example "I understand personalised items cannot be returned".
Opens WPIDE on
Code
$wpide_cat_terms = array(
'categories' => array( 'personalised' ), // Category slugs.
'text' => 'I understand that personalised items are made to order and cannot be returned.',
);
$wpide_cat_terms_needed = function () use ( $wpide_cat_terms ) {
if ( ! WC()->cart ) {
return false;
}
foreach ( WC()->cart->get_cart() as $item ) {
if ( has_term( $wpide_cat_terms['categories'], 'product_cat', $item['product_id'] ) ) {
return true;
}
}
return false;
};
add_action( 'woocommerce_review_order_before_submit', function () use ( $wpide_cat_terms, $wpide_cat_terms_needed ) {
if ( ! $wpide_cat_terms_needed() ) {
return;
}
printf(
'<p class="form-row validate-required wpide-cat-terms"><label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox"><input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="wpide_cat_terms" value="1"> <span>%s</span> <abbr class="required" title="required">*</abbr></label></p>',
esc_html( $wpide_cat_terms['text'] )
);
}, 9 );
add_action( 'woocommerce_checkout_process', function () use ( $wpide_cat_terms_needed ) {
// phpcs:ignore WordPress.Security.NonceVerification -- WooCommerce verifies the checkout nonce.
if ( $wpide_cat_terms_needed() && empty( $_POST['wpide_cat_terms'] ) ) {
wc_add_notice( 'Please confirm you have read the note about personalised items.', 'error' );
}
} );
add_action( 'woocommerce_checkout_order_created', function ( $order ) use ( $wpide_cat_terms ) {
// phpcs:ignore WordPress.Security.NonceVerification -- WooCommerce verifies the checkout nonce.
if ( ! empty( $_POST['wpide_cat_terms'] ) ) {
$order->add_order_note( 'Customer accepted: ' . $wpide_cat_terms['text'] );
}
} );
Notes
The agreement is recorded as an order note so you can show it was accepted.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.