Blog / WordPress/ How to Block Specific Usernames from Registration in WordPress (Code Implementation & Best Practices)

How to Block Specific Usernames from Registration in WordPress (Code Implementation & Best Practices)

WordPress 如何禁止用户注册特定用户名(代码实现与最佳实践)

In website management, restricting the registration of certain usernames is a common security and administrative need. This prevents users from using easily confused administrator names like 'admin' or 'administrator', or registering accounts with names identical to core site pages (e.g., 'login', 'register'), thereby avoiding potential confusion and security risks. Additionally, blocking offensive, abusive, or spam-related terms helps maintain a healthy community environment.

Adding a username blacklist feature to your WordPress site effectively enhances security and management standards. This article provides an optimized and thoroughly explained code solution.

Core Function Code

Add the following code to the end of your current theme's functions.php file, or use a code snippet plugin.

/**
 * WordPress Username Registration Validation Function
 * Purpose: Block usernames in a blacklist and add extra validation rules.
 *
 * @param bool   $valid    Initial validation result.
 * @param string $username The username attempting registration.
 * @return bool  Final validation result (true passes, false rejects).
 */
function wp_custom_validate_username( $valid, $username ) {
    // 1. Define the base array of forbidden usernames.
    $forbidden_names = array(
        'admin',
        'administrator',
        'webmaster',
        'root',
        'system',
        'manager',
        'moderator',
        'support',
        'contact',
        'login',
        'register',
        'wp-admin',
        'wp-login',
        'yourdomain', // Replace with your actual domain
        'test',
        'demo'
    );

    // 2. Automatically get all page slugs and add them to the forbidden list.
    $all_pages = get_pages();
    foreach ( $all_pages as $page ) {
        if ( ! empty( $page->post_name ) ) {
            $forbidden_names[] = $page->post_name;
        }
    }

    // 3. Exemption: Skip if initial validation failed OR if an admin is creating a user.
    if ( ! $valid || ( is_user_logged_in() && current_user_can( 'create_users' ) ) ) {
        return $valid;
    }

    // 4. Begin custom validation.
    $username_lowercase = strtolower( trim( $username ) );

    // Rule 1: Username cannot contain spaces.
    if ( $valid && strpos( $username_lowercase, ' ' ) !== false ) {
        $valid = false;
    }

    // Rule 2: Username must not be in the blacklist.
    if ( $valid && in_array( $username_lowercase, $forbidden_names, true ) ) {
        $valid = false;
    }

    // Rule 3: Username must be at least 4 characters long.
    if ( $valid && strlen( $username_lowercase ) < 4 ) {
        $valid = false;
    }

    // Rule 4: (Example) Username cannot be purely numeric.
    // if ( $valid && is_numeric( $username_lowercase ) ) {
    //     $valid = false;
    // }

    return $valid;
}
add_filter( 'validate_username', 'wp_custom_validate_username', 10, 2 );

/**
 * Custom Registration Error Messages
 * Provides a friendlier error message when a username is rejected.
 *
 * @param WP_Error $errors WP_Error object.
 * @return WP_Error Modified error object.
 */
function wp_custom_registration_errors( $errors ) {
    if ( isset( $errors->errors['invalid_username'] ) ) {
        $errors->errors['invalid_username'][0] = __( 'This username is not allowed or does not meet the requirements. Please try a different one.', 'your-text-domain' );
    }
    return $errors;
}
add_filter( 'registration_errors', 'wp_custom_registration_errors' );

Code Explanation & Configuration

1. Modifying the Forbidden Username List

Locate the $forbidden_names array in the code. You can freely add, remove, or modify the strings. For example, to block 'editor' and 'author', simply add them:

$forbidden_names = array(
    'admin',
    'administrator',
    'editor', // Added
    'author', // Added
    // ... others
);

2. Understanding the Automatic Page Slug Feature

The get_pages() section automatically adds all your site's page slugs (the URL-friendly name, e.g., 'about-us' for an About page) to the forbidden list. This effectively prevents users from registering accounts with names identical to your important pages, avoiding URL conflicts and confusion.

3. Custom Validation Rules

The code includes several core validation rules:

  • No Spaces: Ensures the username is a single, continuous string.
  • Blacklist Check: The core blocking functionality.
  • Minimum Length: Requires at least 4 characters by default. Adjust the number in strlen( $username_lowercase ) < 4 as needed.

A commented example rule for 'blocking purely numeric usernames' is provided. Remove the comments (//) to enable it.

4. Administrator Exemption

Using current_user_can( 'create_users' ), the code skips all custom validation rules when an administrator with 'create users' capability manually adds a user in the dashboard. This ensures admins can register any username when necessary.

Important Notes & Compatibility

  • Plugin Compatibility: This code modifies core WordPress validation hooks and is compatible with most plugins. If conflicts arise, check if other plugins (especially membership or registration plugins) also modify the validate_username or registration_errors filters.
  • Multilingual Support: The error message uses the __( 'text', 'your-text-domain' ) function for translation. Replace your-text-domain with your theme's text domain or use the quoted English text directly.
  • Performance: The automatic fetching of page slugs runs only once during registration, with minimal performance impact. For sites with thousands of pages, consider caching this list.

Implementing this solution allows you to easily and effectively manage username registration on your WordPress site, improving its professionalism and security.

Post a Comment

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