May I know how could I change the error text? Example, I want change it from.
[Error: This username is invalid because it uses illegal characters. Please enter a valid username.]
to
[Error: Username invalid. Please enter a valid username.]
![twuk9 Change WordPress default registration error text [Error: This username is invalid because it uses illegal characters. Please enter a valid username.]](https://magenaut.com/wp-content/uploads/2022/08/twuk9.png)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can achieve this via ‘registration_errors‘ filter hook. The hook filters the WP_Error object that holds all the current errors. The code used will be something like this:
add_filter( 'registration_errors', function( $errors ){
if( $errors->get_error_messages( 'invalid_username' ) ) {
$errors->remove('invalid_username');
$errors->add('invalid_username', '<strong>Error</strong>: My custom error message');
}
return $errors;
});
Please note that we checked the presence of the target error message by its code “invalid_username”, but this code may contain a different message for the username if it is found in the array of ‘illegal_user_logins’ which may contain a list of disallowed usernames, so if you need a different message for the disallowed username error you may use the second parameter “$sanitized_user_login” to check if it’s in the disallowed list and change the error message if so. Your code may be something like this:
add_filter( 'registration_errors', function( $errors, $sanitized_user_login ){
if( $errors->get_error_messages( 'invalid_username' ) ) {
// Get the list of disallowed usernames
$illegal_user_logins = array_map('strtolower', (array) apply_filters( 'illegal_user_logins', array() ));
// Set our default message
$message = '<strong>Error</strong>: My custom error message';
// Change the message if the current username is one of the disallowed usernames
if( in_array( strtolower( $sanitized_user_login ), $illegal_user_logins, true) ) {
$message = '<strong>Error</strong>: My custom error message 2';
}
$errors->remove('invalid_username');
$errors->add('invalid_username', $message);
}
return $errors;
}, 10, 2);
Method 2
Unfortunately you cannot change it, as it is hard-coded and unfiltered in core.
See https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/user.php#L185
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0