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!

With the snippet you find below I’ve added a hidden input field to the WooCommerce My Account login form with name = “redirect”. The input value is populated with the previously visited URL and this will be the URL the login form will redirect to upon successful login.

PHP Snippet: Redirect Users to Previous (Referrer) URL

 * @snippet       Redirect to Referrer @ WooCommerce My Account Login
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli, BusinessBloomer.com
 * @testedwith    WooCommerce 4.6
 * @donate $9     https://businessbloomer.com/bloomer-armada/

add_action( 'woocommerce_login_form_end', 'bbloomer_actual_referrer' );

function bbloomer_actual_referrer() {
	if ( ! wc_get_raw_referer() ) return;
	echo '<input type="hidden" name="redirect" value="' . wp_validate_redirect( wc_get_raw_referer(), wc_get_page_permalink( 'myaccount' ) ) . '" />';

Leave a Reply