In my WP v5.8.1, I am creating new user programmatically from public forms, using wp_create_user
. New user_login will be created by combining first_name
and last_name
$new_username = strtolower(str_replace(' ', '', $_POST['first_name']) . '-' . str_replace(' ', '', $_POST['last_name']));
However, chances are there might be an existing user with same user_login. Hence I want to append number (1,2,3,4,etc) to the new user_login
with below function:
if (username_exists($new_username)) {
create_new_username();
} else {
$new_username = $new_username;
}
function create_new_username() {
$count = 0;
while (username_exists($new_username)) :
$new_username = $new_username . '-' . $count + 1;
$count++;
if (!username_exists($new_username)) {
$create_username = $new_username;
}
endwhile;
return $new_username;
}
echo create_username();
If user_login
exists, the above function returns existing user_login
user ID; it is not creating new user_login
with appending with number.
Edit 1:
I have modified the code as below without writing a separate function:
$new_username = strtolower(str_replace(' ', '', $_POST['first_name']) . '-' . str_replace(' ', '', $_POST['last_name']));
if (username_exists($new_username)) {
$count = 0;
while (username_exists($new_username)) :
$new_username = $new_username . '-' . ($count + 1);
$count++;
endwhile;
}
echo $new_username;
This is returning a new user_login
if user exists; however instead of appending a new series number from ($count + 1)
, it is adding another new number as below:
Whereas I need the usernames like this:
Answering my own question, comments from @Howard E has helped me to achieve what I am looking for:
Below is the new user name created from the public form submission:
$new_username = strtolower(str_replace(' ', '', $_POST['first_name']) . '-' . str_replace(' ', '', $_POST['last_name']));
With below code, I am able to check if the user_login
is exists, if exists appending a serial number to create new user_login
:
if (username_exists($new_username)) { // check if user_login exists
while (username_exists($new_username)) :
$count = preg_match_all("/.*?(\d+)$/", $new_username, $matches); // check if the existing user_login has serialised number at the end
if ($count) { // if user_login has number at the end
$new_username = rtrim($new_username, '-' . $count); // remove the number and '-' also before the number
} else {
$count = 0; // else keep the count as 0 to add to the submitted user_login from the public form
}
$new_username = $new_username . '-' . ($count + 1); // this will create a new serialised user_login with numbering continuation from previous, else create new user_login as per form submission
$count++;
endwhile;
}
echo $new_username;
Now this is creating user_logins as below:
Please comment if the code can be still be more simpler and efficient?