Skip to content

Instantly share code, notes, and snippets.

@levymetal
Last active November 1, 2022 02:42
Show Gist options
  • Save levymetal/03085a8656d8eb104deb to your computer and use it in GitHub Desktop.
Save levymetal/03085a8656d8eb104deb to your computer and use it in GitHub Desktop.
Allow hyphenated usernames in Wordpress Multisite
<?php
/**
* Allow hypenated usernames
*
* @wp-hook wpmu_validate_user_signup
* @param array $result
* @return array
*/
function wpse_59760_allow_hyphenated_usernames( $result ) {
$error_name = $result[ 'errors' ]->get_error_message( 'user_name' );
if ( ! empty ( $error_name )
&& $error_name == __( 'Usernames can only contain lowercase letters (a-z) and numbers.' )
&& $result['user_name'] == $result['orig_username']
&& ! preg_match( '/[^-a-z0-9]/', $result['user_name'] )
) {
unset ( $result[ 'errors' ]->errors[ 'user_name' ] );
return $result;
} else {
return $result;
}
}
add_filter( 'wpmu_validate_user_signup', 'wpse_59760_allow_hyphenated_usernames' );
@call0fcode
Copy link

For those reading this on 2021.

I'm creating a multisite on WordPress 5.6 and I could allow hyphenated and dashed 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]/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment