Search code examples
wordpressgravity-forms-plugin

Add random character to programatically created users username wordpress


I use Gravity forms to programmatically create a user and I want to check if a username exists, and if it does, add random characters after the value from the $username field.

Getting my variable from the Gravity Form field:

$username = rgar( $entry, '16' );

Array that picks it up:

       $user_data = array(
           'user_login' => $username,
           'user_pass'  => $password,
           'user_email' => $email,
           'role'       => 'customer',
           'first_name' => $first_name,
           'last_name'  => $last_name,
       );

Creating the user:

    $user_id  = wp_insert_user( $user_data );

How do I make it so it checks for existing username and if exist, add a random character to the given username?


Solution

  • I think your best shot is to go with a while and keep adding random character to the username until you eventually get a non-existing one.

    Something like this should work:

    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ-_";
    
    while(username_exists($username)){
        $random_character_idx = rand(0,strlen($characters));
        $username .= substr($characters,$random_character_idx,1);
    }
    

    this should keep adding random char to the username until it finds a free one