Check product if already exist in to cart using woocommerce.

Check product if already exist in to cart using woocommerce.

add_action( 'woocommerce_add_to_cart_validation', 'check_product_added_to_cart', 10, 3 );

function check_product_added_to_cart( $passed, $product_id, $quantity) {

foreach (WC()->cart->get_cart() as $cart_key => $cart_item ){
// if products are already in cart:
if( $cart_item['product_id'] == $product_id ) {
// Set the verification variable to "not passed" (false)
$passed = false;
// (Optionally) Displays a notice if product(s) are already in cart
wc_add_notice( '<strong>' . $btn['label'] . '</strong> ' . __( 'This product is already in your cart.', 'woocommerce' ), 'error' );
// Stop the function returning "false", so the products will not be added again
return $passed;
}
}
return $passed;
}

More at https://phpajaxhtml.blogspot.in/2017/11/check-product-if-already-exist-in-to.html