• Resolved Group Of Oceninfo

    (@princebhalani143)


    Hello Team,

    After doing some google and research I found below code which allows only one item to be book at a time.

    /* Clear cart data before adding new */
    // before addto cart, only allow 1 item in a cart
    add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );
     
    function woo_custom_add_to_cart_before( $cart_item_data ) {
     
        global $woocommerce;
        $woocommerce->cart->empty_cart();
     
        // Do nothing with the data and return
        return true;
    }

    I want some functionality when user click on Add to Cart button it’ll clear there previous cart data completely and add new cart data, only allow one product purchase at a time.

    I have used above code but it’s working sometime and sometime it’s not working.

    i.e. If I am login as a admin then I can see multiple product in cart, sometime it’s also doing weird thing on refresh page it’s adding product automatically.

    Can you please help me how I can forcefully clear cart every time when someone click on add to cart button and add new data whatever they have requested?

Viewing 4 replies - 1 through 4 (of 4 total)
  • I have used this code with Woocommerce and it worked great.

    https://businessbloomer.com/woocommerce-allow-1-product-cart/

    Not sure if I’m allowed to add an outside link but Rodolfo has some great snippits.

    Thread Starter Group Of Oceninfo

    (@princebhalani143)

    @wooguy: thank you for your reply but if you see the code which one I have provided is also same except message.

    I looked at one of my other stores and I am using this:

    /*Limits one item per purchase session */
    add_filter( ‘woocommerce_add_cart_item_data’, ‘woo_custom_add_to_cart’ );
    function woo_custom_add_to_cart( $cart_item_data )
    {global $woocommerce;
    $woocommerce->cart->empty_cart();
    return $cart_item_data;
    }

    This is working with Woocommerce 3.2.6

    Let me know if this does not work with Woocommerce 3.3.1 since I will be looking for a fix if that is the case.
    Thanks

    Thread Starter Group Of Oceninfo

    (@princebhalani143)

    Hi Wooguy,

    Thank you for your reply but it’s not working in the same way what I am looking for it’s removing the product and adding new when I am not login to the backend but it’s not working when we are login because whenever I am testing with login as administrator and adding product to cart it’s not removing any previous product.

    Thanks,
    Prince

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to Allow One Item in Cart?’ is closed to new replies.