Remove terms and conditions from WooCommerce checkout page when only specific products are in cart
P粉245003607
2023-07-30 10:35:54
<p>I sell event tickets and accept donations at https://development.pittsburghconcertsociety.org. When someone purchases a ticket, they must agree to the COVID policies. But when someone only "purchases" a donation, i.e. they just put the donation product in their cart, they don't need to agree to the COVID policy. The WooCommerce support chatbot provides the following code, but it doesn't work: </p>
<pre class="brush:php;toolbar:false;">function hide_terms_for_specific_product( $woocommerce_checkout_fields ) {
// Check if the specific product is the only item in the cart
if (WC()->cart) {
$cart_items = WC()->cart->get_cart();
$specific_product_found = false;
foreach ( $cart_items as $cart_item ) {
// Replace '123' with the ID of the specific product
if ( $cart_item['product_id'] == 551 ) {
$specific_product_found = true;
break;
}
}
// Hide terms and conditions for the specific product
if ( $specific_product_found ) {
unset( $woocommerce_checkout_fields['terms'] );
}
}
return $woocommerce_checkout_fields;
}
add_filter( 'woocommerce_checkout_fields', 'hide_terms_for_specific_product' );</pre>
<p>The ID of the donation product is 551). To summarize, I do want to have a T&C checkbox/requirement if there are tickets and donation products in the cart, but no T&C is required if there are only donation products in the cart. In this case, it is not enough to just hide the T&C, it must also not be required. </p><p>Also, if we sell items, it would be nice to be able to add multiple product IDs. </p><p><br /></p>
The following code will completely remove the T&C requirement when only specific products are in the cart:
The code should be placed in the functions.php file of the active child theme, or placed in a plugin. Has been tested and confirmed to work.