How To Programmatically Create a WordPress Admin User

How can I create a WordPress user with admin role programmatically. So new user should have admin rights

To create a WordPress admin user programmatically, it’s similar with creating a new WordPress user but assign with Administrator role.

Firstly you need to check user exists or not by email and then Generating the password for the new user. Finally, Assign the Administrator role to new user

if( null == username_exists( $email_address ) ) {

  // Generate the password and create the user
  $password = wp_generate_password( 12, false );
  $user_id = wp_create_user( $email_address, $password, $email_address );

  // Set the nickname
  wp_update_user(
    array(
      'ID'          =>    $user_id,
      'nickname'    =>    $email_address
    )
  );

  // Set the role
  $user = new WP_User( $user_id );
  $user->set_role( 'administrator' );
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rania
5 years ago

But in this case, I think the password will be random? does your script send out the newly generated password to the email address or no?
Thank you