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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* Generate Unique User Nicename */ function generate_unique_user_nicename( $x ) { // set up args to query $args = array( 'search' => sanitize_title( $x ), 'search_columns' => array( 'user_nicename' ) ); // query for user $user_url_exists = new WP_User_Query( $args ); $results = $user_url_exists->get_results(); // if user url is found, check for new one if( !empty( $results ) ) { $i = substr( sanitize_title( $x ), intval( strrpos( sanitize_title( $x ) ,'-' ) ) + 1 ); if( is_numeric( $i ) ) { $i++; $y = substr($x, 0, strrpos($x,'-' )); $company_name = $y . '-' . $i; } else { $company_name = $x . '-1'; } $new_company_name = sanitize_title( $company_name ); return generate_unique_user_nicename( $new_company_name ); } else { return sanitize_title( $x ); } } |
Using the above code, you would generate a unique user name using by doing the following:
1 |
generate_unique_user_nicename( $username ); |
Using this function inside of wp_update_user()
would look like this:
1 2 3 4 5 |
$userdata = array( 'ID' => $userid, 'user_nicename' => generate_unique_user_nicename( $username ) ); $userid = wp_update_user( $userdata ); |
Hopefully this helps someone down the line!