Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ValeriiVasyliev/bc0e03d4a46750851a736d97ed35973a to your computer and use it in GitHub Desktop.
Save ValeriiVasyliev/bc0e03d4a46750851a736d97ed35973a 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.
*
* @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