WooCommerce: How to Check if Product ID is in the Cart

How to Check if Product ID is in the Cart in WooCommerce

If you need to determine whether a specific product ID is already in the cart on your WooCommerce store, you can do so easily by using the woocommerce_before_cart action hook. This hook is triggered before the cart page is displayed, allowing you to check the cart contents right before the page is rendered.

 

Code Snippet to Check Product ID in WooCommerce Cart

Here’s a simple code snippet that checks whether a specific product ID is in the WooCommerce 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 works by checking the product ID against the IDs of the items currently in the cart. If a match is found, it outputs a message indicating that the product is in the cart; otherwise, it will indicate that the product is not in the cart.

Where to Place the Code

You can place this code snippet in your WordPress theme’s functions.php file or within a custom plugin to ensure it runs correctly on your WooCommerce store. Make sure to replace 123 with the actual product ID you want to check.

Important Considerations

  • Ensure that the functions.php file or plugin is properly set up to prevent any issues when making modifications to your WooCommerce store.
  • If you’re not familiar with PHP or WooCommerce hooks, consider testing this in a staging environment first to avoid breaking your live site.
  • WooCommerce hooks are powerful, but be careful not to overload the page with too many actions or checks that may slow down the site.

External Links and Resources

For more information on WooCommerce hooks and customizing your store, check out the following resources:

Scroll to Top

Request A Quote