I can’t imagine how to verify if the cart has some products inside, or not. I just need to allow ONE product for the checkout.
Here is the code used in class-wc-cart.php to prevent products to be added if THE SAME product is already in the cart, and I’m sure should be pretty similar, but I’m missing some WP variables to define any kind of product.
I tried also with this code, but it doesn’t work in functions.php (no, I’m not using child themes).
if ( $product_data->is_sold_individually() ) {
$in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;
// If it's greater than 0, it's already in the cart
if ( $in_cart_quantity > 0 ) {
wc_add_notice( sprintf(
'<a href="%s" class="button wc-forward">%s</a> %s',
$this->get_cart_url(),
__( 'View Cart', 'woocommerce' ),
sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_title() )
), 'error' );
return false;
}
}
Thank you.
Don’t make changes directly in woocommerce core file because when you update plugin, might your code lost.
Add following code into functions.php and it will add only one product into cart: