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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
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 this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

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? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

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