We’ve already seen how to set a custom My Account login redirect URL by user role – but today we want to cover another case scenario: redirecting users to the previous URL (referrer) after logging in from the My Account page.
Actually, WooCommerce already prints a hidden input field (“_wp_http_referer“) in the login form thanks to wp_nonce_field(), but for some reason this is not enough to allow the actual redirect.
Thankfully, the WooCommerce process_login() function provides another workaround: if $_POST[‘redirect’] is set, the form will consider redirecting to this URL instead of the default My Account Dashboard! This means we can simply add a new hidden field to the login form with that exact name (“redirect”), so that we can make that function trigger the redirect we want.
Easier coded than said, so let’s see how it’s done. Enjoy!
PHP Snippet: Redirect Users to Previous (“Referrer”) URL
/**
* @snippet Redirect to Referrer @ WooCommerce My Account Login
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire, BusinessBloomer.com
* @testedwith WooCommerce 5
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_login_form_end', 'tutoraspire_actual_referrer' );
function tutoraspire_actual_referrer() {
if ( ! wc_get_raw_referer() ) return;
echo '';
}