Disable adding two or more similar products in WooCommerce cart

Sometimes it may be necessary that user can add only one product to cart and if he click on the add this product button again, then the need remove product from the cart.

How add to cart only one product in WooCommerce?

Problem: Add to cart only one product in WooComerce. If user add to cart this product need remove it from cart.

Solution: Ultimately, challenge is to how check current product was added to cart or not? We can resolve the problem 2 ways:

First way:

<?php
$current_product_id = '555';

if ( WC()->cart->get_cart() ) {
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
		if ( $cart_item['product_id'] === $current_product_id ) {
			WC()->cart->remove_cart_item( $cart_item_key );
		} else {
            WC()->cart->add_to_cart( $current_product_id, 1 );	       
        }
	}
}

Second way. At the start few words about WooComerce cart . In the cart generate hash for each product. By the way, this hash we can see in the table on the cart page, in the cell change quantity products or in the URL for product remove. It look like it "53fde96fcc4b4ce72d7739202324cd49".

<?php
$current_product_id = '555';

$product_cart_hash = WC()->cart->generate_cart_id( $current_product_id ); // get hash by product ID
$in_cart = WC()->cart->find_product_in_cart( $product_cart_hash ); // find product to cart by hash
if ( $in_cart ) {
    WC()->cart->remove_cart_item( $product_cart_hash );
} else {
    WC()->cart->add_to_cart( $current_product_id, 1 );	
}

Leave Comment

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