This snippet should only be attempted if you have a basic understanding of PHP and where to place the code.

Sometimes you find yourself needing to check if a customer has an item in the cart to perform certain functions, In this instance we’re going to add a message to the cart. Although there are plugins that can perform this functionality. A much simpler and light-weight solution is to just use a code snippet.

All you’ll require for this is the Product ID, which can be found by simply rolling your mouse over the product in the Products page in your WordPress Dashboard.

 
add_action( 'woocommerce_before_cart', 'thomasdeer_is_product_in_cart' );
function thomasdeer_is_product_in_cart() {
    $p_id = 123; //This is the Product ID we are checking for.
    $item_in_cart = false; //Default is False.

    foreach( WC()->cart->get_cart() as $cart_item ) { //Loops through all product's in the cart
      $is_in_cart = $cart_item['product_id'];
        if ( $is_in_cart === $p_id ) {
            $item_in_cart = true; //We found the item, Mark it as true.
        }
    }

    if ( $item_in_cart ) { //The Item Exists, We do this!
        $notice = 'The item is in the Cart!';
        wc_print_notice( $notice, 'notice' );
    }
}

Essentially what we are doing here, We define the Product ID of the item we are looking for. We then use a foreach loop to loop through the cart items and see if the Product ID matches the product ID we have defined earlier. Then if the Product ID is found, We then print the WooCommerce Notice to the customer.

Obviously this snippet can be expanded a great deal and be used for much more in-depth applications. but this is just the basic usage.


if you require any assitance with this snippet, feel free to Contact Me and i will be happy to assist you.