Using WordPress ‘pre_user_login’ PHP filter

The ‘pre_user_login’ filter allows you to modify the sanitized username before a user is created or updated in WordPress.

Usage

add_filter( 'pre_user_login', 'my_custom_function', 10, 1 );

function my_custom_function( $sanitized_user_login ) {
    // Your custom code here
    return $sanitized_user_login;
}

Parameters

  • $sanitized_user_login (string): The username after it has been sanitized.

Examples

Add a Prefix to the Username

add_filter( 'pre_user_login', 'add_prefix_to_username', 10, 1 );

function add_prefix_to_username( $sanitized_user_login ) {
    // Add 'my_prefix_' to the beginning of the username
    return 'my_prefix_' . $sanitized_user_login;
}

This code adds a prefix ‘my_prefix_’ to the username before it is saved to the database.

Convert Username to Uppercase

add_filter( 'pre_user_login', 'convert_username_to_uppercase', 10, 1 );

function convert_username_to_uppercase( $sanitized_user_login ) {
    // Convert the username to uppercase
    return strtoupper( $sanitized_user_login );
}

This code converts the username to uppercase before it is saved to the database.

Remove Numbers from the Username

add_filter( 'pre_user_login', 'remove_numbers_from_username', 10, 1 );

function remove_numbers_from_username( $sanitized_user_login ) {
    // Remove all numbers from the username
    return preg_replace( '/d/', '', $sanitized_user_login );
}

This code removes any numbers from the username before it is saved to the database.

Replace Spaces with Underscores

add_filter( 'pre_user_login', 'replace_spaces_with_underscores', 10, 1 );

function replace_spaces_with_underscores( $sanitized_user_login ) {
    // Replace spaces with underscores in the username
    return str_replace( ' ', '_', $sanitized_user_login );
}

This code replaces any spaces in the username with underscores before it is saved to the database.

Limit Username Length

add_filter( 'pre_user_login', 'limit_username_length', 10, 1 );

function limit_username_length( $sanitized_user_login ) {
    // Limit the username length to 15 characters
    return substr( $sanitized_user_login, 0, 15 );
}

This code limits the username length to 15 characters before it is saved to the database.