I sell event tickets and accept donations on https://development.pittsburghconcertsociety.org. When someone buys a ticket, they must agree to the covid policies. But when someone only "buys" a donation, i.e. they put only a donation product in the cart, they do not need to agree to covid policies. The woo support chatbot spit out this code, but it’s not working:
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' );
(Donation is product ID 551). To summarize, I do want the T&C checkbox/requirement if a donation is in the cart along with a ticket, but not if a donation is the only item in the cart. And it’s not enough to just hide the T&C in this case; it also needs to not be required.
Gravy: be able to add more than one product ID in case we sell merch.
2
Answers
You were not using the correct hook. The following will remove T&C entirely when a specific product is alone in cart:
Code goes in functions.php file of the active child theme (or in a plugin). Tested and works.
In case it is helpful I created a similar script which enables TOS on products in a specific category only. Also had to add a check for WC()->cart as this sometimes caused a fatal error if null.