Intercept invalid email during lost_password

On the website I’m developing, I need all login-related forms to be on custom, branded pages. I have pretty much covered them all, but I have just one case I can’t manage correctly.

I have set a custom page for the Lost password? page, by adding the filter below, then creating a new page with a custom template that renders the Insert email to get the link form.

function custom_lost_password_page( $lostpassword_url, $redirect ) {
    return home_url( '/lost-password/' );
}
add_filter( 'lostpassword_url', 'custom_lost_password_page', 10, 2 );

On the page template I set a custom redirect_to input field so that the successful request redirects to my custom login page with a specific message.

<input type="hidden" name="redirect_to" value="<?= site_url('/login?resetlink=sent') ?>">

So far so good. What I can’t seem to intercept, is when the user enter a non-existent email. In that case, no matter what, I get redirected to /wp-login.php?action=lostpassword, which is a native WP page we don’t want, with the corresponding error message.

Invalid email screen

I can’t seem to find an action or filter to latch onto in this particular case. Google unfortunately wasn’t of help and all similar questions here don’t seem to handle this very specific case.

Any ideas?
Thanks in advance and have a nice day!

2 Answers
2

Try this:

add_action( 'lost_password', 'wpse316932_redirect_wrong_email' );
function wpse316932_redirect_wrong_email() {
    global $errors;

    if ( $error = $errors->get_error_code() ) {
        wp_safe_redirect( 'lost-password/?error=" . $error );
    } else {
        wp_safe_redirect( "lost-password/' );
    }    
}

This is utilizing the lost_password action hook that fires right before the lost password form.

You were experiencing this because WP will only redirect you to the url you specified in redirect_to input field when there is no errors. If it finds errors in processing the form (which is the obvious case here), it simply continues with rendering the form on the wp-login.php page. By using this action you can hook into this procedure right before that.

Leave a Comment