Allowing WordPress Usernames with Special Characters: The “+” Symbol

Hello, fellow coders! Today, I want to share a solution I got on Stack Overflow for an issue I faced while working on a project. The problem was that I wanted to allow users to create usernames with special characters, specifically the “+” symbol. However, by default, WordPress removes special characters during the registration process. Let’s dive into how to resolve this issue and allow users to create usernames with the “+” symbol.

The Issue

When users tried to register with a username containing the “+” symbol, such as “abcd+123”, WordPress would automatically remove the special character, resulting in a username like “abcd123”. The goal was to keep the “+” symbol in the username.

The Solution

To achieve this, we need to modify the WordPress sanitize_user function by adding a custom filter. The following code snippet is a solution I found on Stack Overflow, which allows the “+” symbol in usernames:

add_filter( 'sanitize_user', 'tubs_sanitize_user', 10, 3);

function tubs_sanitize_user($username, $raw_username, $strict) {
    $new_username = strip_tags($raw_username);
    // Kill octets
    $new_username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $new_username);
    $new_username = preg_replace('/&.?;/', '', $new_username); // Kill entities

    // If strict, reduce to ASCII for max portability.
    if ( $strict )
        $new_username = preg_replace('|[^a-z0-9 _.\-@+]|i', '', $new_username);

    return $new_username;
}

This code is a modified version of the original WordPress sanitize_user function. It includes an extra character “+” in the allowed characters list when the $strict parameter is set.

How to Implement the Solution

To implement this solution, simply add the above code snippet to your theme’s functions.php file or create a custom plugin. Once the filter is in place, WordPress will allow users to register with usernames containing the “+” symbol, as desired.

Happy Coding 🙂