Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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*.

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

There are two very different hooks you can use, depending on the installation:

  • wpmu_validate_user_signup for multi-site and
  • registration_errors for 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 );
}
share|improve this answer
2  
Just be careful what "bad words" filters you use. Some people like "shitake" mushrooms. Or are fans of "classic" music. Or come from a place called "scunthorpe". –  Otto Nov 26 '13 at 22:23
6  
@Otto Or they are from Essex. :) –  toscho Nov 26 '13 at 22:27
    
That was devilish! Works great toscho! –  Christine Cooper Nov 27 '13 at 17:29
3  
Christine, I really wonder how much of your platform toscho already has built :D –  kaiser Nov 27 '13 at 19:52
    
@Otto A fun trivia. We just opened registrations and one new users registered with "ScatArt*..." - Just as we were hitting the ban button, we googled the email address of the user and it appears that it was a genuine registration, no trolling. As if!! –  Christine Cooper Dec 11 '13 at 17:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.