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);