WooCommerce redirect loop when cart and checkout on the same page

I just launched a website with a single page checkout process which works fine if there’s at least one product in the cart.

The problem is if cart an checkout is on the same page and a user tries to access this page without any products in his cart, woocommerce redirects to the cart again and again.

To solve this problem I found this solution:
https://wordpress.org/support/topic/cart-checkout-on-same-page-redirect-loop-problem/

But when an order is finished the cart is empty again so this script redirects again to the home page instead of the order confirmation page.

I improved the script and want to share it with you:

add_action('template_redirect', 'redirection_function');

function redirection_function(){
    global $woocommerce;

    if( is_checkout() && 0 == sprintf(_n('%d', '%d', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count) && !isset($_GET['key']) ) {
        wp_redirect( home_url() ); 
        exit;
    }
}

 

7 Responses to “WooCommerce redirect loop when cart and checkout on the same page”

  1. Dan

    Hi,

    Thanks for writing up your solution, it’s always reassuring to find others have hit the same problem.

    Under Checkout Pages I’ve set both ‘Basket Page’ and ‘Checkout Page’ to /checkout/ and added the cart and checkout shortcodes to the checkout page. This works brilliantly but runs into the issue described above.

    I’ve added your PHP function to my child themes functions.php file but without any success, I still get a redirect loop. Equally clearing the basket via AJAX in the checkout page results in the page eventually crashing.

    Very frustrating!

    Dan

    Reply
    • hannes

      Hi Dan,
      Sorry I don’t have a brilliant idea for you, it took me hours to solve this for myselfes.
      In your situation I’d try to remove the IF-clause to see wether the function has any effect at all. If so then improve the conditions, if not I’d have a look at the theme. Maybe there’s another ‘template_redirect’ hook.

      Reply
  2. Johan

    Hi, thanks for your solution – It works great!

    Could you explain why you’re not simply using
    `if( is_checkout() $woocommerce->cart->cart_contents_count === 0 )`

    instead you’re checking for !isset($_GET[‘key’]) and a plural word of 0 ?

    Reply
    • hannes

      To be honest: I can’t remember, I did this more than 2 years ago 😉

      Reply
  3. ady marwah

    Hi,
    Can you help me
    how to make users redirect to the basket if they add the same product to the basket on one store page and product page
    thank you

    Reply

Leave a Reply