[SOLVED] Allow WordPress to accept plus (+) sign in usernames

September 28, 2016

It was revealed to me recently that a wordpress system which programatically creates user accounts via an external api, where we only allow email addresses as the username, anyone submitting a + sign in the username, the plus sign (+) was being stripped out.

For Example:
joe.bloggs+1@gmail.com was becoming joe.bloggs1@gmail.com (wordpress was stripping out the + sign).

So after a bit of sifting around the interwebs, I came across a plugin which allows foreign characters like Arabic and Cyrillic. So not exactly what I was looking for but I figured I could use some of the code.

Drop the following into your functions.php so that it overrides the filtering of the usernames when sanitize_user is called from WordPress core and edit the $allowed_symbols to permit the characters you would like in the new username when its created.

###################################################
//Allow custom characters inside of wordpress usernames
//USAGE: drop this function and filter into your functions.php file
###################################################
function create_attendee_sanitize_user($username, $raw_username, $strict) {
	
	$allowed_symbols = "a-z0-9+ _.\-@"; //yes we allow whitespace which will be trimmed further down script
	
	//Strip HTML Tags
	$username = wp_strip_all_tags ($raw_username);

	//Remove Accents
	$username = remove_accents ($username);

	//Kill octets
	$username = preg_replace ('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);

	//Kill entities
	$username = preg_replace ('/&.+?;/', '', $username);

	//allow + symbol
	$username = preg_replace ('|[^'.$allowed_symbols.']|iu', '', $username);

	//Remove Whitespaces
	$username = trim ($username);

	// Consolidate contiguous Whitespaces
	$username = preg_replace ('|\s+|', ' ', $username);

	//Done
	return $username;
	
}

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