Generate Unique User Nicenames

Sometimes, you want users to have unique nice names. Here’s a neat little function I wrote to generate a unique nicename for new users. Ultimately, what this function will do is take a string of text and validate it against existing user nice names found on your site. If the nice name is taken, it appends a -1 to the end and re-checks. If that is taken it will append a -2 and re-validate it, and on and on until it returns a valid and unique nice name.

This is a great function used in conjunction with the wp_update_user() function.

Using the above code, you would generate a unique user name using by doing the following:

Using this function inside of wp_update_user() would look like this:

Hopefully this helps someone down the line!

About the Author

Evan Herman

Evan is a full time WordPress developer at Yikes Inc. where he makes all sorts of cool things with WordPress. When he’s not there you can find him developing awesome plugins, blogging about WordPress or hanging out with his three cats and amazing girlfriend in Philadelphia, PA.