fbpx
How to Restrict Usernames in WordPress Without a Plugin

How to Restrict Usernames in WordPress Without a Plugin

Here is a snippet that enables you to restrict certain usernames from being created by new users registering to your WordPress website.

Instructions
Add this code your theme function.php file.
*Remember to replace content of the “restricted array” with the usernames you want to restrict.

function wpsnippet_validate_username($valid, $username) {
    $restricted = array('profile', '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) {
        $restricted[] = $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, $restricted )) $valid=false;
    if ($valid && strlen($username) < 5) $valid=false;
    return $valid;
}
add_filter('validate_username', 'wpsnippet_validate_username', 10, 2);

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

If you want to use a plugin to achieve the same functionality, you can use Scott Reilly’s Restrict Usernames WordPress plugin.

WordPress Snippet Info

Tested with Wordpress v. 4.9.5
Last Modified: 16.08.2015
Last Reviewed: 05.09.2018

How to Restrict Usernames in WordPress Without a Plugin
4 (80%) 4 vote[s]
Please report broken snippets.
Report Broken Snippet

Recent Comments