Skip to content

How To Restrict Usernames In WordPress

If you manage a WordPress blog where anyone can register, then you might wanna restrict usernames in WordPress. If anyone can register in your website, then they can also pick any username, such as moderator, developer, spam, comment, email, download and more.

You can do this job in two ways – with plugin or without plugin. Let’s get started

With Plugin

Restrict Usernames is the most popular plugin when it comes to restrict something in your WordPress username. This plugin allows you to restrict the usernames that new users may use when registering for your WordPress.

Without Plugin

If you don’t want to install a new plugin to your WordPress, then you can also do this job with your functions.php file. This codes comes from sozot.com & it also prevents spaces in usernames which for some strange reason.

Add following snippet to your theme’s functions.php file:

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

You can add as many names as you want in the above code.

1 thought on “How To Restrict Usernames In WordPress”

  1. any way to prevent partially matching usernames? i can restrict the use of “admin” but i can’t restrict every possible usernames containing “admin” such as “joeadmin” or “alexadmin” and so on.

Leave a Reply

Your email address will not be published. Required fields are marked *