Last active
February 11, 2023 19:05
-
-
Save philipnewcomer/59a695415f5f9a2dd851deda42d0552f to your computer and use it in GitHub Desktop.
Generate a unique username in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Recursive function to generate a unique username. | |
* | |
* If the username already exists, will add a numerical suffix which will increase until a unique username is found. | |
* | |
* @param string $username | |
* | |
* @return string The unique username. | |
*/ | |
function generate_unique_username( $username ) { | |
static $i; | |
if ( null === $i ) { | |
$i = 1; | |
} else { | |
$i++; | |
} | |
if ( ! username_exists( $username ) ) { | |
return $username; | |
} | |
$new_username = sprintf( '%s-%s', $username, $i ); | |
if ( ! username_exists( $new_username ) ) { | |
return $new_username; | |
} else { | |
return call_user_func( __FUNCTION__, $username ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
New here on GitHub but I thought I'd share my take on this code. My website does not allow user registration. Users are currently created manually. This will allow for use of a csv file (via plugin) to load new users and ensure unique usernames. I replaced the recursive function calls with a while loop. Because of where I hooked into sanitize_user is already performed by the .../includes/user.php edit_user function. Because of hook location removal of the registration error is required.