8

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.

11

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.

7

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.

  • 1
    I will mark your one as correct, although real answer turned out to be as simple as update_option('default_role', 'custom_role_name') upon activation of the plugin. – jayarjo Oct 22 '11 at 9:05
  • Glad to have been of help. – soulseekah Oct 22 '11 at 9:09
2

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

1

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

//Make 'Client' a default role

update_option('default_role','client');
  • 2
    Why?? It serves no purpose to put your code somewhere without knowing what it does or how it works – Pieter Goosen Sep 16 '15 at 19:58
  • That's not good solution. This will run update query if not put in special action on each request. – Maciej Paprocki Apr 2 '18 at 19:33

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.