How do I programmatically set default role for new users?

I would like new users of the blog to have custom role, rather then Subscriber. How do I set this programmatically? I know that it can be changed from the backend.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This allows plugins to easily hijack the default role while they’re active.

// Hijack the option, the role will follow!
add_filter('pre_option_default_role', function($default_role){
    // You can also add conditional tags here and return whatever
    return 'subscriber'; // This is changed
    return $default_role; // This allows default
});

I use it to make sure some plugins that need subscriber roles get it regardless of Administrator attempts to change 🙂

Regards.

Method 2

When a new user is created through the wp_insert_user() function, the role is set with the set_role() method of the User class and is set to the default user role.

The default user role is retrieved from the database get_option('default_role') and can be set via the Admin Dashboard by going to Settings > General > New User Default Role.

If you’ve registered your new role (using add_role(), it should be available there to choose from.

Alternatively, for more control you can hook into the user_register or profile_update actions to then set_role on them conditionally, or however else you like.

Method 3

After you created the user using

$user_id = wp_create_user( $user_login, $pas1, $user_email );

Create the user object

$user = new WP_User($user_id);

Then set the role

$user->set_role('editor');

You can replace the ‘editor’ role with any of the following:

  • Administrator
  • Editor
  • Author
  • Contributor
  • Subscriber

Method 4

Put it into the Pluging or functions.php of your theme

//Make 'Client' a default role

update_option('default_role','client');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x