Forked from philipnewcomer/generate-unique-username.php
Created
November 15, 2022 03:06
-
-
Save ValeriiVasyliev/bc0e03d4a46750851a736d97ed35973a 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. | |
* | |
* @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