When the cart is empty, it shows a button to “Return to shop”.
By default, as it says, it returns to the shop page selected in the settings. But you can change that URL to something else.
To do so, add this code to your functions.php file located in wp-content/themes/your-theme-name/:
This will redirect to the URL specified in the code.
What if you want to dynamically return to the page previously visited?
Use this code instead:
Be aware that it will return to the previous visited page. So if you were on the cart page while it was not empty, and then removed everything in it, the referrer URL will be the non-empty cart page.
You would need to add some additionals check to be sure that the referrer URL is not the cart page.