Adding Custom Roles and Capabilities to WordPress

Hopefully saving future me problems.

Yesterday I said that the big bug I encountered when dealing with roles and capabilities on a client site was me. Today let's look at how add a role properly and extend it to have a few extra capabilities that are needed for our platform.

For our platform we have "Custom Administrators" that should be able to do some of the things that a regular WordPress Administrator should be able to do, like create_users or delete_users. The WordPress Codex has a nice table that makes it clear what capabilities every role has.

Instead of adding these capabilities to the standard Editor role we're going to create a new role that gets the regular capabilities of the Editor, then we'll layer the extra capabilities on top of that to extend the role.

add_action('init', array( $this, 'addRole'));

/**
* Adds new Admin Role
*
* @uses get_role() Returns user role object
* @uses add_role() Creates new role given args
* @uses add_cap()  Adds capabilities to role object
*
* @return null
*/
function addRole()
{
    $editor = get_role('editor');

    add_role('custom_admin', 'Custom Admin', $editor->capabilities);

    // adding extra roles our new admin needs
    $intranet_admin = get_role('proudcity_admin');
    $intranet_admin->add_cap('custom_admin');
    $intranet_admin->add_cap('create_users');
    $intranet_admin->add_cap('delete_users');
    $intranet_admin->add_cap('edit_users');
    $intranet_admin->add_cap('list_users');
    $intranet_admin->add_cap('customize');
    $intranet_admin->add_cap('remove_users');

}

Note that I also added a custom capability of custom_admin. This will let me use a conditional to detect only the new Custom Admin role and allow users with it access to any extra things we may add to the site. To get either regular WordPress Administrators or our new Custom Administrator I could use a conditional like this.

if (current_user_can('custom_admin') || current_user_can('activate_plugins')){
    // do stuff here for either Administrators or Custom Administrators
}

Yes I could modify the code above to add the custom_admin capability to WordPress Administrators, but in this instance I prefer to leave the stock role alone. If I was adding a new feature to the site that needed it's own custom capabilities I would add it to the roles that needed it, but this isn't a new feature it's just a new role so I can control what some users are allowed to do.

I'd put this code in a custom plugin which would hold any further modifications I'd want to make to our roles on the site.