0

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','testusers@mailaccount.tk');
        $user = new WP_User( $user_id );
    $user->set_role( 'author' );
    }

Thanks in advance!

3

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','testusers@mailaccount.tk');
    $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','testusers@mailaccount.tk');
    $user = new WP_User( $user_id );
    $user->remove_role( 'subscriber' );
    $user->add_role( 'author' );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.