questions

how to clear the login fields on incorrect credentials WP

Rate this post

I found this code snippet on the web to insert into my function.php file to customize the error message so that it is more secure:

// custom the login error message
function customize_login_errors(){
    return 'The login credentials are incorrect.';
}
add_filter( 'login_errors', 'customize_login_errors' );

Although, I have found a loophole.

If the username is incorrect, the username input field gets clears along with the password. Perfect, just what I want. However, if I enter the username correctly, the field’s input remains upon entering an invalid password. Although, this is more secure than the default error message, it still let unwanted guests know if they have guessed a valid username.

How do I take it a step further and clear both the username/email and password fields upon entering invalid credentials?

 

✔️Solution:

I would inject the following javascript snippet to the login page when the login fails!

Put this javascript into a file called, let’s say, custom_error_login.js

jQuery(document).ready(async function ($) {

  await new Promise(r => setTimeout(r, 200));

  $("input#user_pass").val("").blur();

  $("input#user_login").val("").focus();

});

And then put the following snippet in your functions.php of your active child/theme and use the following hook to inject it to the login page after login fails!!!

add_filter('login_errors', 'my_custom_login_failure');

function my_custom_login_failure()
{
    global $errors;

    $error_codes = $errors->get_error_codes();

    // Invalid username.
    if (in_array('invalid_username', $error_codes)) {
        $error = '<strong>Invalid credentials!!!</strong>';
    }

    // Incorrect password.
    if (in_array('incorrect_password', $error_codes)) {
        $error = '<strong>Invalid credentials!!!</strong>';
    }

    remove_action('login_footer', 'wp_shake_js', 12); // removing the shaking effect of the form, snippet could work without this line too!!!  

    wp_enqueue_script('jquery');

    wp_enqueue_script('my_custom_login_script', get_theme_file_uri('path/to/js_folder/custom_error_login.js'), 'JQuery', "1.0", TRUE);

    
    return $error;
}

Leave a Reply

Your email address will not be published.

Back to top button