简体   繁体   中英

Product not adding in cart after add_filter() on woocommerce_add_to_cart_validation

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 ie 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;

You need to return the cart item data, if the number of products is only 1:

function woocommerce_add_cart_myfunction( $cart_item_data ) {

    $numberOfProducts = WC()->cart->cart_contents_count;
    if ( $numberOfProducts > 1 ) {
         wc_add_notice(
                     __( 'You cannot add another product to your cart.'.$numberOfProducts, 'woocommerce' ));
         return false;
    }

    return $cart_item_data;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM