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' );
}
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.
This is your error
It’s is because of
$user->remove_role( 'subscriber' );
code and it means that, when you are using following code to retrieve the new userIt’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 usedIt’s possible that, you didn’t successfully created a user and in this case the return value could be an
object
according toCodex
SO, when you are creating a user, at first check if the user exist or not like
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
.Check to make sure that
wp_create_user()
actually created the user: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
get_user_by()
wp_create_user()