If you need to determine whether a specific product ID is already in the cart on your WooCommerce store, you can easily do that using the woocommerce_before_cart
action hook. This hook is triggered just before the cart page is rendered, giving you the opportunity to inspect the cart contents and perform conditional logic.
Code Snippet to Check Product ID in WooCommerce Cart
Here’s a straightforward PHP snippet to check whether a given product ID is currently in the cart:
add_action('woocommerce_before_cart', 'check_product_id_in_cart'); function check_product_id_in_cart() { $product_id_to_check = 123; // Replace 123 with the ID of the product you want to check $product_in_cart = false; // Get the cart contents $cart_items = WC()->cart->get_cart(); // Loop through the cart items foreach ($cart_items as $cart_item_key => $cart_item) { $product_id = $cart_item['product_id']; // Check if the product ID is in the cart if ($product_id === $product_id_to_check) { $product_in_cart = true; break; } } if ($product_in_cart) { // Product ID is in the cart, do something echo 'The product is in the cart.'; } else { // Product ID is not in the cart, do something else echo 'The product is not in the cart.'; } }
How It Works
This code loops through all items in the WooCommerce cart and compares each item’s product ID with the one you’re checking for. If a match is found, a message is displayed accordingly.
Where to Place the Code
Add the above code snippet into your theme’s functions.php
file or in a custom plugin to make sure it executes correctly on your WooCommerce cart page.
Important Considerations
- Ensure your
functions.php
or plugin file is error-free and doesn’t conflict with other code. - Always test changes on a staging site before applying them to a live store.
- Limit the number of hooks/actions to avoid performance degradation.