WordPress code on how to create user & set role and permission

many times there is needed to create a WordPress user from coding-end to make a frontend registration form. And for that, we need to create a user programmatically and set rools of the user and give the user permission.

WordPress User Creation Form

WordPress User Creation Form

 

now we will learn how we can make a user using WordPress code

Step 1.

Take the value of the user to be created in the variable

$user = 'hiran';
$pass = '123456';
$email = '[email protected]';
$user_url = 'https://wordpress.org';
$first_name = 'Wxyz';
$last_name = 'Abcd';
$description = 'I am a developer';

Step 2.

now check if the user already exists or not

if( !username_exists( $user )  && !email_exists( $email ) ){ 
}else{ 
   echo "The email or username alrady exist";
}

Step 3.

Now create the user and get the created user id inside the if condition using the code:

$user_id = wp_create_user( $user, $pass, $email );

Step 4.

Now create an instance or object of the created user by using the fetched userid the code is:

$user = new WP_User( $user_id );
<
pre>

Step 5.

Now set the role of the created user by using the code:

$user->set_role( 'administrator' );
you can create  ‘subscriber’ or ‘contributor’ or ‘author’ or ‘editor’ or ‘administrator’ by using the keywords given under ”.

 

Step 6.

Now update the user with the details, using the code

$user_id = wp_update_user( array( 'ID' => $user_id, 'user_url' => $user_url, 'first_name' => $first_name, 'last_name' => $last_name, 'description' => $description ) );

Step 7.

And finally, check if there is an error during the creation of the WordPress user

if ( is_wp_error( $user_id ) ) { //There was an error, probably that user doesn't exist.} else { // Success!}

And you have successfully created a WordPress user and here is the full code for creating a WordPress user and set role and permission

$user = 'hiran';
$pass = '123456';
$email = '[email protected]';
$user_url = 'https://wordpress.org';
$first_name = 'Wxyz';
$last_name = 'Abcd';
$description = 'I am a developer';

if( !username_exists( $user )  && !email_exists( $email ) ){ 
   $user_id = wp_create_user( $user, $pass, $email ); 
   $user = new WP_User( $user_id ); 
   $user->set_role( 'administrator' ); 
   // subscriber | contributor | author | editor | administrator

   $user_id = wp_update_user( array( 'ID' => $user_id, 'user_url' => $user_url, 'first_name' => $first_name, 'last_name' => $last_name, 'description' => $description ) );
   
   if ( is_wp_error( $user_id ) ) { 
      //There was an error, probably that user doesn't exist. 
   } else { 
      // Success! 
   }
}else{ 
   echo "The email or username alrady exist";
}

 

Thanks for reading

Share The Post On -