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?

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:

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.