Skip to content

Instantly share code, notes, and snippets.

@raazon
Created September 18, 2020 20:25
Show Gist options
  • Save raazon/bf7d9826b9acfb45eecb470d39e47c35 to your computer and use it in GitHub Desktop.
Save raazon/bf7d9826b9acfb45eecb470d39e47c35 to your computer and use it in GitHub Desktop.
Generate a unique username in WordPress
<?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