How do I add a filter to the username field to stop new users from registering using unwanted words such as administrator or general profanity?
Ideally, if I could add a large list of words that are blocked with the option to add asterisk (*) as a wildcard like genitals*.
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
There are two very different hooks you can use, depending on the installation:
wpmu_validate_user_signupfor multi-site andregistration_errorsfor single-site.
The following untested code shows how to use them. You can tweak the array in user_name_is_forbidden() to your needs. Use regular expressions for the matches.
// multi-site
add_filter( 'wpmu_validate_user_signup', function( $result )
{
// there is already an error
if ( $result['errors']->get_error_message('user_name') )
return $result;
if ( user_name_is_forbidden( $result['user_name'] ) )
$result['errors']->add('user_name', __( 'That username is not allowed.' ) );
return $result;
});
//single-site
add_filter( 'registration_errors', function( $errors, $name )
{
if ( user_name_is_forbidden( $name ) )
$errors->add('user_name', __( 'That username is not allowed.' ) );
return $errors;
}, 10, 2);
function user_name_is_forbidden( $name )
{
// If you need the character '~', write it as '~'.
$forbidden = array(
'admin.*',
'genitals.*',
'system.*'
);
return (bool) preg_match( '~' . join( '|', $forbidden ) . '~i', $name );
}
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