Set user ID at time of wp_create_user

I’d like to add a new user to the WordPress user table. The code for wp_create_user works fine but it is adding the user incrementally to the next available ID in the user table.

Instead, I want to create the user and assign it to a particular user ID. The user ID is already available (externally) and I want the ID entered into the WordPress database to match the external one.

Read More
$user_login = $username ;
$pas1 = $email_address;
$user_email = $email_address;

wp_create_user( $user_login, $pas1, $user_email );
$user = new WP_User($user_id);
$user->set_role('editor'); 

For example, I want to know how to set the known $user_id at the time of wp_create_user.

Related posts

2 comments

  1. wp_insert_user will not create a non-existing user with a set ID, it will return an error.

    The way to do this would be to first do:

    global $wpdb;
    
    $wpdb->insert( $wpdb->users, array( 'ID' => 136166 ) );
    
    wp_insert_user( ... );
    

    The code above will first create an empty user row with the set ID (it will fail hard if the ID already exists, duplicate entry for primary key ) which you can then modify using the API as needed.

  2. Not with wp_create_user(). Check the source:

    1518  function wp_create_user($username, $password, $email = '') {
    1519          $user_login = wp_slash( $username );
    1520          $user_email = wp_slash( $email    );
    1521          $user_pass = $password;
    1522  
    1523          $userdata = compact('user_login', 'user_email', 'user_pass');
    1524          return wp_insert_user($userdata);
    1525  }
    

    https://core.trac.wordpress.org/browser/tags/3.8.1/src/wp-includes/user.php#L1518

    wp_create_user doesn’t accept an ID argument. However, take a look at the function used at the bottom of wp_create_user(). wp_insert_user() does honor an ID argument.

    The downside is that it will overwrite an existing user with the same ID, so you will need to write the logic to handle that case.

Comments are closed.