Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>';
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>';
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading