1

I'm developing an plugin that adds an new user role (client role, for instance). This role only extends the admin role for now.

add_role(
    'client',
    __('Client'),
    get_role('administrator')->capabilities
);

Now i wan't to release an new version of the plugin that update the client capabilities and remove the install_plugins capability.

Roles are persistent, so i can't just update my add_role.

My question is: how can i manage an custom role, updating it's capabilities?

1 Answer 1

2

Off the top of my head, you should be able to do something like this:

$role = get_role( 'client' );

if ( $role && $role->has_cap( 'install_plugins' ) ) {
  // Role not updated yet, so update it.
  $role->remove_cap( 'install_plugins' );
}

get_role() returns a WP_Role object on success and WP_Role::remove_cap() calls WP_Roles::remove_cap(), which directly updates the option in the database. The $role->has_cap() check ensures that the code isn't run twice.

Running this in a function hooked to init should suffice.

Ideally you'd have a database version option for your plugin which you could use to run some code exactly once per plugin update. Otherwise your code is executed again every time someone manually adds the install_plugins capability to your role again. That's not necessarily bad, but it could be prevented :-)

Code reference:

2
  • Good explanation. For my plugin, the best choice is an database version manager. I will try to implement it. Commented Jan 15, 2018 at 16:48
  • I have another question that is related to this one, but about an specific hook. Can you check it? wordpress.stackexchange.com/questions/291134/… Commented Jan 15, 2018 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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