Woocommerce code on checkout page for a message

As you can see from this question I’m pretty naive when it comes to this sort of stuff.
I have found some code to use to leave a message on the checkout page when a certain item is in the basket, that item can only be bought on it’s own, all that works great.

What I want to do is amend the code so that a different message is displayed if it’s any other items in the cart.

add_action( 'woocommerce_before_checkout_form', 'allclean_add_checkout_content', 10 );
function allclean_add_checkout_content() {
    // set your products IDs here:
    $product_ids = array( 97406);
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) )
            $bool = true;
    }
    // If the special cat is detected in one items of the cart
    // It displays the message
    if ($bool)
        echo '<div class="checkoutdisc"><b>My Message: </b>Text in here.</div>';
}

>Solution :

So in the following code I check if the special product is in the cart. If it is, $special_product_in_cart is set to true.

If $special_product_in_cart is true, it displays the special message. else it displays a general message.

add_action( 'woocommerce_before_checkout_form', 'allclean_add_checkout_content', 10 );

function allclean_add_checkout_content() {
    $special_product_id = 97406;
    $special_product_in_cart = false;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $product_id = $cart_item['product_id'];
        
        if ( $product_id == $special_product_id ) {
            $special_product_in_cart = true;
            break; // Stop the loop if special product found
        }
    }

    // If the special product is in the cart then display the special message
    if ($special_product_in_cart) {
        echo '<div class="checkoutdisc"><b>My Message for Special Product: </b>Text in here for special product.</div>';
    } else {
        // Else display a general message for other products
        echo '<div class="checkoutdisc"><b>General Message: </b>Text in here for other products.</div>';
    }
}

Leave a Reply