WooCommerce: Check if Product ID is in the Cart

Here’s the story: I’m working with one of my freelance clients and I need to show certain content in the Checkout (a product-specific “Terms and Conditions”) if such product is in the Cart.

Now, I’ve always looked for products in the Cart by “looping” through the Cart with a foreach (here, for example: Apply a Coupon Programmatically if a Product is in the Cart). But as I said, after some random research, I found out about another magic WooCommerce function: “find_product_in_cart()“. Which means finding a product in the Cart doesn’t require custom loops or complex PHP… it’s just a “one liner”. Enjoy!

WooCommerce: find if product ID is in the Cart

PHP Snippet: Easily Check if Product ID is Contained in the Cart – WooCommerce

Note: I believe this method only works with “simple” products. In case, use the snippet alternative you find below.

/**
 * @snippet       Check if Product ID is in the Cart - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.9
 * @community     https://businessbloomer.com/club/
 */
  
add_action( 'woocommerce_before_cart', 'bbloomer_find_product_in_cart' );
   
function bbloomer_find_product_in_cart() {
 
   $product_id = 282;
 
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
 
   if ( $in_cart ) {
 
      $notice = 'Product ID ' . $product_id . ' is in the Cart!';
      wc_print_notice( $notice, 'notice' );
 
   }
 
}

PHP Snippet Alternative (the “old” way, still works): Check if Product ID is in the Cart Via a Foreach Loop – WooCommerce

/**
 * @snippet       Check if Product ID is in the Cart (Alternative) - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.9
 * @community     https://businessbloomer.com/club/
 */
  
add_action( 'woocommerce_before_cart', 'bbloomer_find_product_in_cart_alt' );
   
function bbloomer_find_product_in_cart_alt() {
 
   $product_id = 282;
   $in_cart = false;
 
   foreach( WC()->cart->get_cart() as $cart_item ) {
      $product_in_cart = $cart_item['product_id'];
      if ( $product_in_cart === $product_id ) $in_cart = true;
   }
 
   if ( $in_cart ) {
 
      $notice = 'Product ID ' . $product_id . ' is in the Cart!';
      wc_print_notice( $notice, 'notice' );
 
   }
 
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: How to Fix the “Cart is Empty” Issue
    For some reason, sometimes you add products to cart but the cart page stays empty (even if you can clearly see the cart widget has products in it for example). But don’t worry – it may just be a simple cache issue (and if you don’t know what cache is that’s no problem either) or […]
  • WooCommerce: “You Only Need $$$ to Get Free Shipping!” @ Cart
    This is a very cool snippet that many of you should use to increase your average order value. Ecommerce customers who are near the “free shipping” threshold will try to add more products to the cart in order to qualify for free shipping. It’s pure psychology. Here’s how we show a simple message on the […]
  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]
  • WooCommerce: Weight-Based Shipping Methods
    With WooCommerce you get 3 default shipping methods: Flat Rate, Free Shipping, Local Pickup. For each one you can define a cost, however there is no way to set up some “weight” restrictions. So, what if you want to display a rate for orders below 10 kg, and another shipping rate for orders above that […]
  • WooCommerce: Hide Shipping Method If Shipping Class Is In The Cart
    Our goal is to check if a Product with a specific Shipping Class is in the Cart, and consequently disabling a shipping rate such as Free Shipping if this is true. This is super useful when there are multiple items in the cart and you don’t want to give free shipping for certain orders for […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

26 thoughts on “WooCommerce: Check if Product ID is in the Cart

  1. Hi!

    How can I display an alternative message if the product has no been added to the cart?

    I tried the following code but it doesn’t work (I’m not a developer ;D).

    if ( $in_cart ) {
            $notice = 'Positive message.'; // Specific product has been added 
            wc_print_notice( $notice, 'notice' );
        } else {
            $notice = 'Alternative message.'; // Specific product has not been added 
            wc_print_notice( $notice, 'notice' );
        }
    
    1. Hello Maina, that should definitely work – as long as your cart is not empty.

      p.s. I never delete questions that are relevant, such as yours.

  2. Hi Rodolfo, I used the alternative snippet – it seems that the first one indeed does not work with variable products. Client uses WordPress 5.5 + Divi 4.6.0 + PHP 7.3 and all works perfectly. Thank you.

    1. Thank you! First snippet will return Variation ID and not Product ID if product is variable I think

  3. How to show the message in the Checkout page instead?

  4. What about:

    	function woo_in_cart($id){ //check if product is in the cart
    		return in_array($id, array_column(WC()->cart->get_cart(), 'product_id'));
    	}

    and you can call it

    if(woo_in_cart($id)){ ...

    Beautifully working 🙂

    1. Whatever works for you 🙂

  5. Hi there Rodolfo,

    I’ve learnt so much from all your previous posts. Many thanks.

    I am now trying to get the post ID for a variation product from the

    $cart_item['data']

    object. Basically I have data in the custom fields which I need to pull into the cart item. It works for other products because the product ID seems to be the same as the post ID. but for variation products, it pulls the variation ID instead.

    Do you know of the best way to get the post ID for variation product within the cart?

    Many thanks in advance

    1. Not to worry. I figured it out : )

      if ( isset (  $product->variation_id  ) ) {
      
                  $product_id   = wp_get_post_parent_id( $product->variation_id );
      
              }else{
                  
                  $product_id = $product->get_id();
      
              } 
      1. Well done!

  6. In order to check if a specific product id is in the cart (both for simple and variable products) you can use this:

    function product_is_in_cart( $product_id ) {
    $product_ids = array_column( WC()->cart->get_cart(), 'product_id' );
    return in_array( $product_id, $product_ids );
    }
    

    It’s not working for variations.

    1. Ok thanks

  7. @Alessandro,

    I had the same problem for multiple products. I came with this snippet:

     
    $product_id = array(144,146,157,698,701);
     
    	foreach ($product_id as $product_id => $product) {
    	 
    	    $product_cart_id = WC()->cart->generate_cart_id( $product );
    	    $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
    	 
    	    if ( $in_cart ) {
    	 
    			$notice = '<p>Let op: Levering voorjaar 2019 !!</p>';
    	        wc_print_notice( $notice, 'notice-delivery' );
     
        	}
        
    	}
    
    
  8. The snippet it doesn’t work with latest woocommerce version. Only the old way works now.

    Tried on latest woocommerce with astra theme and Code Snippets plugin. No other plugin enabled.

    1. Hey Michael, thanks for your comment! Have you tried the “old way” snippet as well? Did that work?

  9. Thank you for this snippet! I’m trying to do some complex cart / order manipulations and these code snippets are really useful.

    1. Excellent, thank you so much Anca!

  10. Hey there,

    I came across this blog which is excellent btw to try to implement something similar where I am trying to add an extra step on checkout when product id 3255 is begin select but I keep getting the follow fatal error –> Fatal error: Call to a member function generate_cart_id() on a non-object. It is complaining about the following line –> $product_cart_id = WC()->cart->generate_cart_id( $product_id );

    Any idea?
    Thank you

    1. Hello Paul, thanks so much for your comment! I just retested this on the latest version of WooCommerce and it still works. Unfortunately this looks like custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R

  11. Hi Rodolfo!
    Is it possible to treat $product_id as an array and check for multiple ids all at once?
    I’d like to check if at least one product of a list is in the cart in orde to add another product as a free gift.
    What do you think about?
    Thanks in advance for your reply.

    1. Hey Alessandro, thanks so much for your comment! Yes, you can look for multiple “needles” in a PHP array: https://stackoverflow.com/questions/7542694/in-array-multiple-values

      Hope this helps!

  12. Wonder if there’s something similar for product category?

    1. Hey Vuster, thanks for your comment! You could get a list of IDs inside your category, and then use this 🙂

  13. Love WooCommerce ….. most of the time 🙂
    So simple to work with.
    find_product_in_cart() was new to me … I will test it -Thanks

    1. Glad this helped 🙂

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *