Meta Tags

Allow Spaces in Usernames – wpmu_validate_user_signup

Due to an integration with an external system that allows spaces, various characters, uppercase letters and numbers we had to adapt our usernames for WordPress to comply with those standards.  During the research to find a solution that did not involve changing the core WordPress files and that would work on a multi-site we came across the filter wpmu_validate_user_signup (located in the file wp-includes/ms-functions.php).  We had originally thought that we could just unset the specific error that was doing the check; however, after WordPress version 4.0 the WP-Error class turned the variable to private making it not possible to unset the array value.  A new method called remove was introduced with version 4.1 that now allows you to remove that specific error from the array.

The problem with that solution is within the error code ‘user_name’ there are other checks that we would still like to leave in place (like if that username already exists).  Therefore, we have opted to loop through the various error messages and only remove the single error message that we are concerned with.

The following code can be added to your themes function.php file or better yet the child themes function.php file.


add_filter( 'wpmu_validate_user_signup', 'wpse_user_names_with_spaces' );

/**
* Allow user names with spaces and other characters.
*
* @wp-hook wpmu_validate_user_signup
* @param array $result
* @return array
*/

function wpse_user_names_with_spaces( $result )
{
//creae a temp WP_Error object
$tempErrors = new WP_Error();

//iterate through the existing user_name errors and only not add the lowercase letters, taking into account localization
if (!empty($result['errors'])) {
for ($i=0; $i < count($result['errors']->errors[ 'user_name' ]); $i++) {
$temp = $result['errors']->errors[ 'user_name' ][$i];
if ($temp !== __( 'Only lowercase letters (a-z) and numbers are allowed.' )) {
$tempErrors->add('user_name', __( $result['errors']->errors[ 'user_name' ][$i] ) );
}
}

//reassign the errors without the space error
$result[ 'errors' ] = $tempErrors;

return $result;
}

}