Remove terms and conditions from WooCommerce checkout page when only specific products are in cart
P粉245003607
P粉245003607 2023-07-30 10:35:54
0
1
509
<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>
P粉245003607
P粉245003607

reply all(1)
P粉344355715

The following code will completely remove the T&C requirement when only specific products are in the cart:

add_filter( 'woocommerce_checkout_show_terms', 'remove_terms_and_conditions_for_specific_unique_item' );
function remove_terms_and_conditions_for_specific_unique_item( $show_terms ) {
    // Replace "123" with the desired product ID
    $targeted_id = 15;
    $cart_items = WC()->cart->get_cart(); // get cart items

    // Check if there is only one item in cart
    if( count($cart_items) > 2 ) {
        return $show_terms;
    }        
    // Check if the targeted product ID is the only item in cart
    if ( reset($cart_items)['product_id'] == $targeted_id ) {
        return false; // Remove terms and conditions field
    }
    return $show_terms;
}

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template