Created
September 18, 2020 20:25
-
-
Save raazon/bf7d9826b9acfb45eecb470d39e47c35 to your computer and use it in GitHub Desktop.
Generate a unique username in WordPress
This file contains hidden or 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. | |
* | |
* REF: https://gist.github.com/philipnewcomer/59a695415f5f9a2dd851deda42d0552f | |
* | |
* @param string $username | |
* | |
* @return string The unique username. | |
*/ | |
function generate_unique_username($username) | |
{ | |
$username = sanitize_user($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