13

I need to add new user with admin role via code, and I found this code:

add_action('init', 'add_user');
function add_user() {
    $username = 'username123';
    $password = 'pasword123';
    $email = 'drew@example.com';

    // Create the new user
    $user_id = wp_create_user( $username, $password, $email );

    // Get current user object
    $user = get_user_by( 'id', $user_id );

    // Remove role
    $user->remove_role( 'subscriber' );

    // Add role
    $user->add_role( 'administrator' );
}

here

But when I added it in functions.php, I got this error :

 Fatal error: Call to a member function remove_role() 
 on a non-object in ..../functions.php on line ...

I also tried this code:

 function fb_wp_insert_user() {
$user_data = array(
'ID' => '',
'user_pass' => wp_generate_password(),
'user_login' => 'dummy',
'user_nicename' => 'Dummy',
'user_url' => '',
'user_email' => 'dummy@example.com',
'display_name' => 'Dummy',
'nickname' => 'dummy',
'first_name' => 'Dummy',
'user_registered' => '2010-05-15 05:55:55',
'role' => get_option('default_role') // Use default role or another role, e.g. 'editor'
);
$user_id = wp_insert_user( $user_data );
}
add_action( 'admin_init', 'fb_wp_insert_user' );

I changed default role to adminstrator but when I browsed the users, I found this user without any role.

Community
  • 1
  • 1
Jlil
  • 321
  • 2
  • 7
  • 17

4 Answers4

16

This is your error

Fatal error: Call to a member function remove_role() on a non-object in ..../functions.php on line ...

It's is because of $user->remove_role( 'subscriber' ); code and it means that, when you are using following code to retrieve the new user

$user = get_user_by( 'id', $user_id );

It's not returning a WP_User object. So, if you call a method on a non object, this error shows up and it could be because you didn't get an ID when you used

$user_id = wp_create_user( $username, $password, $email );

It's possible that, you didn't successfully created a user and in this case the return value could be an object according to Codex

When successful - this function returns the user ID of the created user. In case of failure (username or email already exists) the function returns an error object, with these possible values and messages;

empty_user_login, Cannot create a user with an empty login name.

existing_user_login, This username is already registered.

existing_user_email, This email address is already registered.

SO, when you are creating a user, at first check if the user exist or not like

add_action('init', 'add_my_user');
function add_my_user() {
    $username = 'username123';
    $email = 'drew@example.com';
    $password = 'pasword123';

    $user_id = username_exists( $username );
    if ( !$user_id && email_exists($email) == false ) {
        $user_id = wp_create_user( $username, $password, $email );
        if( !is_wp_error($user_id) ) {
            $user = get_user_by( 'id', $user_id );
            $user->set_role( 'administrator' );
        }
    }
}

Also, there is no need for reomving and adding the role, set_role($role) will remove the previous roles of the user and assign the user the new one. Read more about wp create user and get user by on Codex. Also, check the wp_generate_password() to use a secured password instead of plain text.

Update :

add_user is a WordPress function, so change the name to something else like, add_my_user.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • @RCV please put full code , i use your code and see this : Cannot redeclare add_user() (previously declared in ..\functions.php:909) in ..\wp-admin\includes\user.php on line 18 . 909 is : $username = 'username123'; . maybe i am not understand you correctly . please put your full code. – Jlil Nov 07 '13 at 20:55
  • ooooops same error !! Fatal error: Cannot redeclare add_user() (previously declared in ..\functions.php:909) in ..\wp-admin\includes\user.php on line 18 , 909 is $username = 'username123'; – Jlil Nov 07 '13 at 21:08
  • Check the update, Changed `add_user` to `add_my_user` @techno. – The Alpha Nov 07 '13 at 21:11
  • 1
    If you´re not using this in a plugin, don't forget to use the: require_once "wp-load.php"; – Paulo Costa Jul 07 '19 at 02:46
7

Check to make sure that wp_create_user() actually created the user:

add_action('init', 'add_user');
function add_user() {
    $username = 'username123';
    $password = 'pasword123';
    $email = 'drew@example.com';

    $user = get_user_by( 'email', $email );
    if( ! $user ) {

        // Create the new user
        $user_id = wp_create_user( $username, $password, $email );
        if( is_wp_error( $user_id ) ) {
            // examine the error message
            echo( "Error: " . $user_id->get_error_message() );
            exit;
        }

        // Get current user object
        $user = get_user_by( 'id', $user_id );
    }

    // Remove role
    $user->remove_role( 'subscriber' );

    // Add role
    $user->add_role( 'administrator' );
}

Edited: Per the comments below, it appears that the user has already been created. I've updated the code to check for that. (In essence, now, if the user doesn't already exist, it'll be created.)

References

Pat J
  • 528
  • 10
  • 21
  • Parse error: syntax error, unexpected ';' in ..\functions.php on line 917 . line 917 is : echo( "Error: " . $user_id->get_error_message(); – Jlil Nov 07 '13 at 20:03
  • Whoops, fixed my typo. – Pat J Nov 07 '13 at 20:04
  • Fatal error: Cannot redeclare add_user() (previously declared in ..\functions.php:909) in ..\wp-admin\includes\user.php on line 18 909 is : $username = 'username123'; – Jlil Nov 07 '13 at 20:08
  • @AmalMurali Huh? If `wp_create_user()` returns a `WP_Error` object, I check to see what the error is. Otherwise, `$user` should be a `WP_User` object, unless, for some reason, `wp_create_user()` returned *neither* an integer ID nor a `WP_Error` object. – Pat J Nov 07 '13 at 20:16
  • @AmalMurali i got the error message : "Error: " . $user_id->get_error_message() , the user is already registered – Jlil Nov 07 '13 at 20:59
4
$userData = array(
            'user_login' => 'username',
            'first_name' => 'First',
            'last_name' => 'Last',
            'user_pass' => 'password',
            'user_email' => 'you@mail.com',
            'user_url' => '',
            'role' => 'administrator'
        );
wp_insert_user( $userData );
Jakir Hossain
  • 2,457
  • 18
  • 23
-1
function kechweb_create_admin_account(){
  $user = 'Username'; <br />
  $pass = 'Password';<br />
  $email = 'email@domain.com';<br />
  //if a username with the email ID does not exist, create a new user account<br />
  if ( !username_exists( $user ) && !email_exists( $email ) ) {<br />
  $user_id = wp_create_user( $user, $pass, $email ); <br />
  $user = new WP_User( $user_id ); <br />
  //Set the new user as a Admin <br />
  $user->set_role( 'administrator' ); <br />
  } } <br />
  add_action('init','kechweb_create_admin_account');
Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
  • 1
    Please explain how your answer solves the original question and which information it brings which has not already been brought in the other answers. – jpeg Jan 09 '19 at 12:07