Custom error messages for login and lost password forms

admin2025-01-07  4

When a user enters wrong username/email or password in the login form, I want them to see "Invalid username/email or password." error message. That's easy to do with the following code:

add_filter('login_errors', create_function('$a', "return '<b>Error:</b> Invalid username/email or password.';"));

But with this code, the error message is displayed also in the lost password form. And the part with the wrong password doesn't make sense here, because you enter only username or email.

I found this / but since I don't code, I don't know how to use it or even if it's possible.

Would anyone know how to do this?

When a user enters wrong username/email or password in the login form, I want them to see "Invalid username/email or password." error message. That's easy to do with the following code:

add_filter('login_errors', create_function('$a', "return '<b>Error:</b> Invalid username/email or password.';"));

But with this code, the error message is displayed also in the lost password form. And the part with the wrong password doesn't make sense here, because you enter only username or email.

I found this https://wordpress.org/support/topic/password-reset-message-if-user-is-invalid/ but since I don't code, I don't know how to use it or even if it's possible.

Would anyone know how to do this?

Share Improve this question asked Dec 5, 2022 at 9:53 user9646910user9646910 1 2
  • create_function will generate errors on newer versions of PHP, you should switch away from that style of code, though by using create_function you're actually overcomplicating how it works and making things harder – Tom J Nowell Commented Dec 5, 2022 at 10:12
  • Check out my answer. It will resolve your query. – Harit Panchal Commented Dec 5, 2022 at 11:32
Add a comment  | 

1 Answer 1

Reset to default 0

Try this snippet. You can add custom error messages based on different error codes.

add_filter( 'login_errors', 'custom_login_errros_callback' );

function custom_login_errros_callback( $error ) {
    global $errors;
    $err_codes = $errors->get_error_codes();

    if ( in_array( 'invalid_username', $err_codes ) ) {
        $error = '<b>Error:</b> Invalid username/email or password.';
    }

    if ( in_array( 'incorrect_password', $err_codes ) ) {
        $error = '<b>Error:</b> Invalid username/email or password.';
    }

    if ( in_array( 'empty_username', $err_codes ) ) {
        $error = '<b>Error:</b> Invalid username/email or password.';
    }

    if ( in_array( 'empty_password', $err_codes ) ) {
        $error = '<b>Error:</b> Invalid username/email or password.';
    }

    return $error;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252083a17.html

最新回复(0)