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:
- first-last
- first-last-1
- first-last-1-2
- first-last-1-2-3
Whereas I need the usernames like this:
- first-last
- first-last-1
- first-last-2
- first-last-3
2
Answers
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:
With below code, I am able to check if the
user_login
is exists, if exists appending a serial number to create newuser_login
:Now this is creating user_logins as below:
Please comment if the code can be still be more simpler and efficient?
Your function
create_new_username()
needs the variable$new_username
it’s not automatically passed to this function, and therefore is undefined.Then however you’re getting to your
if(username_exists())
call… I’d have to assume through some other hook, you would have to pass the variable$new_username
to yourusername_exists()
function.Since your
else
doesn’t do anything, it’s not necessary.$new_username
already is equal to$new_username