If you create a network of sites using the WordPress Multisite feature, you’ll notice that you aren’t allowed to add users with hyphens (or dashes) in their username.
Unfortunately it seems to be quite difficult to fix this problem, however I came across a post by toscho on WordPress Stackexchange that helped me write a solution.
Drop this code in your functions.php file (remember to remove the <?php at the top) and you’ll be allowed to register users with hyphens in their username.
If you take a look at the original wpmu_validate_user_signup function in wp-includes/ms-functions.php, you’ll notice that I’ve slightly modified the regex test to allow for a hyphen. Of course, you can also add your own regex if you want to allow other characters as well.
If this post has helped you out, feel free to consider throwing a small donation my way.
Comments are closed.
6 comments
For those reading this on 2021.
I’m creating a multisite on WordPress 5.6 and I could allow hyphenated usernames by changing the following on the original wpmu_validate_user_signup function in wp-includes/ms-functions.php:
function wpmu_validate_user_signup( $user_name, $user_email ) {
...
if ( $user_name != $orig_username || preg_match( '/[^-_a-z0-9]/', $user_name ) ) {
$errors->add( 'user_name', __( 'Usernames can only contain lowercase letters (a-z), -, _ and numbers.' ) );
$user_name = $orig_username;
}
...
}
Just change the regular expression to be: /[^-_a-z0-9]/
It isn’t really safe to change code in wp-includes as WordPress may update core code automatically at any time. Also it might not be possible for people running managed installations.
The safest way to modify behaviour is via hooks – does the hook not work in 5.6?
Didn’t try it cause I’m kinda newie working with WordPress, but I’m going to do a research and change code correspondingly. It makes sense what you say that the WordPress core may be changed in coming versions and thus the changed functionality. Thanks for the tip! 😉
Just wanted to note: Still works fine, as soon as you change the translated text to the new wording in https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/ms-functions.php#L420, which is:
__( ‘Usernames can only contain lowercase letters (a-z) and numbers.’ )
Thanks,
Christian
Cheers for the info mate, the snippet has now been updated with the new translation string!
Awesome, that’s what i call a quick reaction. Thanks!