I am running WordPress 4.7.5 and I am trying to set user roles programmatically for a customer. However set_role
does not seem to have any effect.
The user is created, but the users role is subscriber. I also tried different roles, such as $user->set_role('administrator')
– also to no avail.
Here is my code – what am I doing wrong?
require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
if ( !username_exists( 'mytestuser' ) ) {
$user_id = wp_create_user('mytestuser', 'testpass345','[email protected]');
$user = new WP_User( $user_id );
$user->set_role( 'author' );
}
Thanks in advance!
1 Answer
You can use wp_update_user
to update the role for your newly created user.
if ( !username_exists( 'mytestuser' ) ) {
$user_id = wp_create_user('mytestuser', 'testpass345','[email protected]');
$user_id = wp_update_user( array( 'ID' => $user_id, 'role' => 'author' ) );
}
Further reading at WordPress Codex.
Or, you can remove the current role and assign a new one:
if ( !username_exists( 'mytestuser' ) ) {
$user_id = wp_create_user('mytestuser', 'testpass345','[email protected]');
$user = new WP_User( $user_id );
$user->remove_role( 'subscriber' );
$user->add_role( 'author' );
}