我需要通过代码添加具有管理员角色的新用户,我找到了这段代码:
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' );
}
但是当我添加它时functions.php
,我得到了这个错误:
Fatal error: Call to a member function remove_role()
on a non-object in ..../functions.php on line ...
我也试过这段代码:
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' );
我将默认角色更改为,adminstrator
但是当我浏览用户时,我发现这个用户没有任何角色。