Redirecting to the Store Front When You Empty the Cart

Redirecting to the Store Front When You Empty the Cart

I noticed today a question on the BigCommerce forum asking if it was possible to get the cart to redirect to the front page if everything was emptied out of the cart. The reply from one of the support staff said it was impossible to do so because you need access to the PHP source code, which of course BC won’t allow.

Always up for a challenge, especially when I see such big claims that something is impossible, I headed for the template file editor and opened up cart.html, and after a few moments of experimenting, I concluded that it is entirely possible to create the redirect.

Here’s how, in three easy steps:

  1. Click Design and open the Template Files tab. Find cart.html in the file list, and click edit.
  2. In the editor, scroll to the bottom of the file, and locate the closing </body> tag.
  3. Paste in the following code above the tag:

<script type="text/javascript"><br> $(document).ready(function(){<br> if (!$('.ProductName').length) {<br> setTimeout("window.location = '/';",2000);<br> }<br> });<br> </script>

[alert style=”green”]This is an updated code snippet. Previously I suggested searching for the success message and empty cart message and if both existed, the redirect would activate. This worked fine, however when a user clicked the update quantity button, it would also trigger the redirect.

It took a little while to discover why, but the empty cart message is always present, hidden with CSS. The new selector .ProductName only appears when there are items in the cart, so we check to see if it’s not there.[/alert]

And there we have it. Test it out by adding an item to your cart in the frontend, opening the cart, and then clicking Remove. After two seconds, the empty cart redirects to your store index page.

Just a few notes to explain the following:
setTimeout("window.location = '/';",2000);

“window.location = ‘/’;” – replace the ‘/’ with any path you require for your redirect destination.
2000 is a time, in milliseconds, until the redirect activates.