1
votes

I have a Woocommerce form to 'Add Funds'. It has an amount input field ($20, $30 ...etc.) and a submit button that redirects to cart page with the input amount as total.

Redirect to checkout is working, but the cart items are not getting removed if a user abandons the cart and tries to order again.

I tried numerous solutions for the redirect to checkout, but only one worked.

Working solution for redirect to checkout:

WooCommerce - Skip cart page redirecting to checkout page

Solutions not working for redirect to checkout:

https://wordpress.stackexchange.com/questions/267071/redirect-to-woocommerce-checkout-after-adding-to-cart-item-already-in-cart

Woocommerce add to cart button redirect to checkout

N.B. I have added the working and not working solutions for redirect to checkout because it may provide an insight as to why the empty cart solutions are not working.

Incase of emptying cart before adding a new product, none of the solutions are working:

https://gist.github.com/viniciusrtf/b49403b5f87dcd7699c1

https://hungred.com/how-to/empty-woocommerce-cart-adding-item/

https://wordpress.stackexchange.com/questions/267071/redirect-to-woocommerce-checkout-after-adding-to-cart-item-already-in-cart

Using Woocommerce 3.2.6 and WordPress 4.9.2

1

1 Answers

4
votes

First you will need in WooCommerce Settings > Products > Display in "Add to cart behaviour" to enabled the checkbox : Redirect to the cart page after successful addition

Then you will need the 3 following hooked function:

1) Empty cart before add-to-cart (if cart is not empty)

add_filter( 'woocommerce_add_to_cart_validation', 'one_cart_item_at_the_time', 10, 3 );
function one_cart_item_at_the_time( $passed, $product_id, $quantity ) {
    if( ! WC()->cart->is_empty())
        WC()->cart->empty_cart();
    return $passed;
}

2) Add-to-cart redirection to checkout:

add_filter( 'woocommerce_add_to_cart_redirect', 'add_to_cart_checkout_redirection', 10, 1 );
function add_to_cart_checkout_redirection( $url ) {
    return wc_get_checkout_url();
}

3) Skip cart page redirecting to checkout:

add_action('template_redirect', 'skip_cart_page_redirection_to_checkout');
function skip_cart_page_redirection_to_checkout() {
    if( is_cart() )
        wp_redirect( wc_get_checkout_url() );
}

Code goes in function.php file of your active child theme (or active theme).

Tested and works (with Woocommerce 3.2.6 and WordPress 4.9.2 on Storefront theme).