WooCommerce Detect if the Same Product is Already in the Cart

Are you creating a shopping system in WooCommrce where you would not like users to purchase the same product twice? This guide is going to illustrate how to detect if the same product is already in the cart in woocommerce.

There’re many scenarios that you would not like a user to add the same product twice to the cart, for example, when creating a subscription system and only one subscription is needed, at this point, you would not like users to add the same item to the cart twice.

We’ill be editing the child theme’s fucntions.php, please see a complete guide on how to create a child them without coding in WordPress.

We are going to detect if the same product is already in the cart and if the product is already in the cart, we will redirect the user to the checkout page. You can take any action you want.

If you would like to allow only one item in the cart at a time, that is,  you don’t want multiple items to be added to the cart, please see this guide.

This guide will only detect if the same item is already in the cart in woocommerce. To give a good explanation, let’s say you have product A and product B. You can add product A and Product B to the cart but you cannot add two product A or two product B to the cart.

The following code will detect if the same product is already in the cart in woocommerce and if the same product is already in the cart,  we will redirect the customer to checkout.

See the code below

function is_the_same_product_in_the_cart($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_the_same_product_in_the_cart',11,3);

 

 

 

 

 



AdBlock Detected!
This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker or pausing adblock for this website.