To check if a specific product ID is in the cart in WooCommerce, you can use the `woocommerce_before_cart` action hook, which is fired before the cart page is displayed. Here’s how you can achieve this:
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.'; } }
Replace `123` with the ID of the product you want to check. This code will run when the cart page is loaded, and it will check if the specified product ID is in the cart. If the product ID is found in the cart, it will display “The product is in the cart.” If the product ID is not in the cart, it will display “The product is not in the cart.”
Remember to place this code snippet in your theme’s `functions.php` file or in a custom plugin to ensure it runs properly on your WooCommerce store.