Check if item already in cart – WooCommerce

By | August 13, 2018

In WooCommerce, Looking for code by which you can check Product that you going to ADD to CART already exist in Cart or not ?
By Below code you can check whether an item has already been added to your WooCommerce cart or not ?

# $product_id is ID for product which you going to Add to Cart
global $woocommerce;
 
    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];
 
        if($product_id == $_product->id ) {
            return true;
        }
    }
 
    return false;

With use of above code you can implement login like it same Product already exist in Cart than instead of adding more time or showing Error / Warning Message specially for a digital products redirect them to Cart Or Checkout page.

function is_product_in_same_cat($valid, $product_id, $quantity) {
    global $woocommerce;
    //if($woocommerce->cart->cart_contents_count == 0){ return true;}
	if($woocommerce->cart->cart_contents_count > 0){
		foreach($woocommerce->cart->get_cart() as $key => $val ) {
			$_product = $val['data'];
	 		if($product_id == $_product->id ) {
				$url = WC()->cart->get_checkout_url();
				wp_redirect($url);
				exit;
			}
		}
	}
	return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_in_same_cat',11,3);