While working on a client site recently I noticed that when using a custom login form (such as a page with Divi’s Login module), when a user enters incorrect login credentials they’re redirected to the wp-admin login instead of back to the custom form.
This is less than ideal, considering if we’ve created a custom login form we want the user to stay on the form.
After some quick Googling, I found many solutions but they only solved half the problem – they only worked if the user entered an incorrect username/password combination and didn’t leave either field blank.
However, if the user left the fields blank and submitted the form, the authentication function never runs so the user is still redirected to the wp-login page.
Since I couldn’t find any usable solutions, I decided to put together a few ideas to make this work properly. Here is the full code to keep failed login attempts on your custom login form. You can add it to your child theme’s functions.php file.
function wpcc_front_end_login_fail( $username ) {
$referrer = $_SERVER['HTTP_REFERER'];
if ( !empty( $referrer ) && !strstr( $referrer,'wp-login' ) && !strstr( $referrer,'wp-admin' ) ) {
$referrer = esc_url( remove_query_arg( 'login', $referrer ) );
wp_redirect( $referrer . '?login=failed' );
exit;
}
}
add_action( 'wp_login_failed', 'wpcc_front_end_login_fail' );
function custom_authenticate_wpcc( $user, $username, $password ) {
if ( is_wp_error( $user ) && isset( $_SERVER[ 'HTTP_REFERER' ] ) && !strpos( $_SERVER[ 'HTTP_REFERER' ], 'wp-admin' ) && !strpos( $_SERVER[ 'HTTP_REFERER' ], 'wp-login.php' ) ) {
$referrer = $_SERVER[ 'HTTP_REFERER' ];
foreach ( $user->errors as $key => $error ) {
if ( in_array( $key, array( 'empty_password', 'empty_username') ) ) {
unset( $user->errors[ $key ] );
$user->errors[ 'custom_'.$key ] = $error;
}
}
}
return $user;
}
add_filter( 'authenticate', 'custom_authenticate_wpcc', 31, 3);
The above code will keep failed login attempts on your custom login page and append ?login=failed to the URL, so you can display a custom error message if you’d like.
Have a better way? Drop it in the comments below and let’s talk about it!
As always, happy creating!