Filter username field on registration for profanity and unwanted words

The question:

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

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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


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

Leave a Comment