Want to verify if a specific product is already in the WooCommerce cart? This can be done easily using the woocommerce_before_cart action hook, which executes right before the cart page is displayed. It’s a handy place to inject logic like this.
Code Example: Check Product ID in Cart
Here’s a simple code block that lets you check whether a certain product ID is present in the user’s 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 the Code Works
The snippet loops through the cart contents and compares each product’s ID with the one you’re targeting. Depending on whether it matches, a message is printed.
Best Place to Add This Code
Place this code inside your theme’s functions.php file or inside a small custom plugin to execute it properly on the cart page.
Things to Keep in Mind
- Test thoroughly in a staging environment before deploying to production.
- Don’t clutter your theme with too many hook-based checks for performance reasons.
- Be sure to replace the
123with the correct product ID you want to monitor.
Helpful Resources
