I’m trying to override the authenticate to edit the default error message.
/**
Purposed: Custom Login Error Message
Description: This function override the default error message on login form.
**/
remove_filter( 'authenticate', 'wp_authenticate_username_password' );
add_filter( 'authenticate', 'custom_authenticate_username_password', 30, 3 );
/**
* Remove WordPress filer and write our own with changed error text.
*/
function custom_authenticate_username_password( $user, $username, $password ) {
if ( is_a($user, 'WP_User') )
return $user;
if ( empty( $username ) || empty( $password ) ) {
if ( is_wp_error( $user ) )
return $user;
$error = new WP_Error();
if ( empty( $username ) )
$error->add('empty_email', __('The username or email field is empty.'));
if ( empty( $password ) )
$error->add('empty_password', __( 'The password field is empty' ));
return $error;
}
$user = get_user_by( 'login', $username );
if ( !$user )
return new WP_Error( 'invalid_username', sprintf( __( 'Invalid username or email address.' ), wp_lostpassword_url() ) );
$user = apply_filters( 'wp_authenticate_user', $user, $password );
if ( is_wp_error( $user ) )
return $user;
if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) )
return new WP_Error( 'incorrect_password', sprintf( __( 'The password you've entered is incorrect.' ),
$username, wp_lostpassword_url() ) );
return $user;
}
Unfortunately, the empty username or password error is not overriding.
The default error message for username and password are;
<strong>Error</strong> : The username field is empty.
<strong>Error</strong> : The password field is empty.
I would like to change it to;
The username or email field is empty.
The password field is empty.
However, the invalid_username
and incorrect_password
are working and I successfully override it.
2
Answers
The following code is the reason why it doesn't overriding.
Try to remove this condition.
It should be something like this.
Notice that I added braces to every condition to make it more clear.
You might also want to override the function
wp_authenticate_email_password
.There are two functions under
authenticate
,wp_authenticate_username_password
andwp_authenticate_email_password
. Try to override both of them, maybe one of them has the error message that is not overriding, use the codes above and examine.You have an or statement and an individual statement, it’s only going to return one. Try changing it around a little:
Updated
Regardless of how you would like to structure your code, I added the
$error->get_error_messages();
at the end of the error. For more more information, you can have a look at this information: https://code.tutsplus.com/tutorials/wordpress-error-handling-with-wp_error-class-i–cms-21120