我需要通过代码添加具有管理员角色的新用户,我发现了以下代码:
add_action('init', 'add_user');
function add_user() {
$username = 'username123';
$password = 'pasword123';
$email = '[email protected] /cdn-cgi/l/email-protection';
// 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 https://stackoverflow.com/questions/17308808/create-an-admin-user-programmatically-in-wordpress
但是当我添加它时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' => '[email protected] /cdn-cgi/l/email-protection',
'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
但当我浏览用户时,我发现该用户没有任何角色。