I have a scenario in which a non logged user can only add 1 product in his cart. I am adding a filter on woocommerce_add_to_cart_validation
which works fine with $woocommerce->cart->cart_contents_count>0
i.e. it displays a notice You cannot add another product to your cart.0
however, if I do $woocommerce->cart->cart_contents_count>1
the page just refresh without adding anything into cart.
Below is my custom function for doing that.
if(!is_user_logged_in()):
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_cart_myfunction' );
function woocommerce_add_cart_myfunction( $cart_item_data ) {
global $woocommerce;
$numberOfProducts=$woocommerce->cart->cart_contents_count;
if($numberOfProducts > 1){
wc_add_notice(
__( 'You cannot add another product to your cart.'.$numberOfProducts, 'woocommerce' ));
return false;
}
}
endif;