2
votes

I have skipped the cart on my course membership site so 'Buy Now' brings you straight to checkout.

However, if you were logged in when you clicked 'Buy Now' then exit without buying, the item remains in the cart the next time you are logged in. If you go to purchase the same item during the next visit, it says "This item is already in your cart" but since I have the cart hidden from the front end, they can't access it.

Is it possible to empty the cart when page reloads with WooCommerce so it always goes straight to checkout when the user clicks 'Buy Now'?

2

2 Answers

3
votes

Seems you're selling product individually. In this solution we're bypassing the filter hook woocommerce_add_to_cart_sold_individually_found_in_cart. When $found_in_cart is true users getting the message "This item is already in your cart". That's why we're resetting the quantity to 1. For more details please check https://docs.woocommerce.com/wc-apidocs/source-class-WC_Cart.html#1064

function op_bypass_add_to_cart_sold_individually_found_in_cart( $found_in_cart, $product_id ) {
    if ( $found_in_cart ) {
        $cart_contents = WC()->cart->get_cart_contents();
        foreach ( $cart_contents as $key => $item ) {
            if ( $product_id === $item['product_id'] ) {
                WC()->cart->set_quantity( $key, 1 );
                break;
            }
        }
        return false;
    }
    return $found_in_cart;
}
add_filter( 'woocommerce_add_to_cart_sold_individually_found_in_cart', 'op_bypass_add_to_cart_sold_individually_found_in_cart', 10, 2 );
0
votes

In my case " WC()->cart->set_quantity( $key, 1 );" from the answer @obiPlabon didn't worked proper, so I simplified function.

Since $found_in_cart is already fire only when amount of sold individually products in cart is more then one, I decided to simplify code and just make redirect to checkout page just it run.

if ( $found_in_cart ) {
        global $woocommerce;
        wp_redirect( wc_get_checkout_url() );
        exit;
}