Short description of the problem: (and possible solution)
when wordpress creates the user's nicename ("A string that contains a URL-friendly name for the user").
If you specified a Hebrew username this will be a list of html entities.
In my test, the Hebrew username was "בדיקהקהקהק" with a sanitized username of "%d7%91%d7%93%d7%99%d7%a7%d7%94%d7%a7%d7%94%d7%a7%d7%a7" (54 characters).
The lenght of field user_nicename is 50 characters in the wordpress database. (this explains by the way, why it worked with usernames up to 8 characters)
Taking a look at the Wordpress code of user.php, we can see that Wordpress is checking the length of user_nicename
before inserting the user, but it doesn't work.
Let me show you why:
the code to check user_nicename
length is something like this:
$user_nicename = sanitize_user( $userdata['user_nicename'], true );
if ( mb_strlen( $user_nicename ) > 50 ) {
return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
}
When using a Hebrew username, regardless of the length of the generated user_nicename
, the condition will always be true because the function sanitize_user()
"removes all unsafe characters" - including html entities, and returns an empty string, length = 0.
Eventually passing the check you could have the impression that the user was created without error, but it wasn't because of the data exceeding the field length in user_nicename
.
Possible solutions are to programmatically cut the string to 50 characters, forcing some stacig user_nicename
like "user-1", "user-2" etc, or using latin characters for user_nicename
either with PHP Transliterator class or a custom library/function.
I picked the last solution and because I used shared hosting without an option to install additional libraries.
Working code
inserted into function.php of my template:
// user creation with Hebrew usernames
//function to transliterate username
function convert_user_nicename($hebrew_username) {
$charset = array('א'=>'a','ב'=>'b','ג'=>'g','ד'=>'d','ה'=>'h','ו'=>'v','ז'=>'z','ח'=>'h','ט'=>'t','י'=>'y','ך'=>'k','כ'=>'k','ל'=>'l','ם'=>'m','מ'=>'m','ן'=>'n','נ'=>'n','ס'=>'s','ע'=>'e','ף'=>'p','פ'=>'p','ץ'=>'ts','צ'=>'ts','ק'=>'q','ר'=>'r','ש'=>'sh','ת'=>'t');
$latin_user_slug = '';
$chars = mbStringToArray($hebrew_username);
foreach ($chars as $key =>$char) {
$latin_user_slug .= $charset[$char];
}
return($latin_user_slug);
}
function mbStringToArray ($string) {
$strlen = mb_strlen($string);
while ($strlen) {
$array[] = mb_substr($string,0,1,"UTF-8");
$string = mb_substr($string,1,$strlen,"UTF-8");
$strlen = mb_strlen($string);
}
return $array;
}
// remove the filter
remove_filter( 'pre_user_nicename', 'filter_pre_user_nicename', 10, 1 );
function filter_pre_user_nicename($user_nicename) {
$heb = html_entity_decode($user_nicename);
$user_nicename = convert_user_nicename($heb);
return $user_nicename;
};
// add new filter
add_filter( 'pre_user_nicename', 'filter_pre_user_nicename', 10, 1 );