WooCommerce: Check if Product ID is in the Cart

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.

Categories

Related Blogs

Adding Sidebar In WordPress Theme

Adding a sidebar to a WordPress theme involves modifying the theme files and registering a new sidebar area using WordPress functions. Below are the general steps to add a sidebar in WordPress themes:

Top Quick View Plugins WooCommerce

There are several popular WooCommerce quick view plugins that provide a convenient way for customers to view product details without leaving the current page. Keep in mind that the popularity of plugins can change over time, so it’s a good idea to check for the latest information and reviews before making a decision.