Updates, Tips & Tricks

Updates as Released, Plus My Personal Collection Of WordPress Best Practices

WordPress Username Restrictions without a Plugin

26 April

On a recent project my client needed WordPress username restrictions but didn’t want to use a plugin. There are a few plugins out there that allow username restrictions but they are a bit overkill for this project and so I decided to just implemented it via a snippet in functions.php.

Basically, there’s a list of forbidden terms that you can easily expand. It also queries the list of pages and forbids usernames that match page names. It’s easy to expand the list of forbidden usernames and also you could change the get_pages query to include posts or other custom post types if that’s applicable for your application. It also prevents spaces in usernames which for some strange reason, isn’t default behavior in WordPress. Go figure. Anyway … enjoy…

//WordPress Username Restrictions
function sozot_validate_username($valid, $username) {
    $forbidden = array('directory', 'domain', 'download', 'downloads', 'edit', 'editor', 'email', 'ecommerce', 'forum', 'forums', 'favorite', 'feedback', 'follow', 'files', 'gadget', 'gadgets', 'games', 'guest', 'group', 'groups', 'homepage', 'hosting', 'hostname', 'httpd', 'https', 'information', 'image', 'images', 'index', 'invite', 'intranet', 'indice', 'iphone', 'javascript', 'knowledgebase', 'lists','websites', 'webmaster', 'workshop', 'yourname', 'yourusername', 'yoursite', 'yourdomain');
    $pages = get_pages();
    foreach ($pages as $page) {
        $forbidden[] = $page->post_name;
    if(!$valid || is_user_logged_in() && current_user_can('create_users') ) return $valid;
    $username = strtolower($username);
    if ($valid && strpos( $username, ' ' ) !== false) $valid=false;
    if ($valid && in_array( $username, $forbidden )) $valid=false;
    if ($valid && strlen($username) < 5) $valid=false;
    return $valid;
add_filter('validate_username', 'sozot_validate_username', 10, 2);

function sozot_registration_errors($errors) {
    if ( isset( $errors->errors['invalid_username'] ) )
        $errors->errors['invalid_username'][0] = __( 'ERROR: Invalid username.', 'sozot' );
    return $errors;
add_filter('registration_errors', 'sozot_registration_errors');

There you have it, a simple method for WordPress username restrictions that doesn’t require a plugin.

Before you go, you may want to take a moment to browse through my heavily discounted Premium WordPress Themes, Plugins & Extensions.