Control Capabilities with Custom User Roles

in WordPress Tutorials

WordPress comes with several preset roles, such as Editor, Author, Contributor, etc, that can be used to control what logged in users can and cannot do. There are a lot of situations, however, where the default user roles may not be sufficient for the task at hand. When that happens, it may be necessary to create your own custom user roles.

There is a built-in function called add_role() that allows us to create a custom user role, to which we can grant any and all capabilities we wish.

The function looks like this:

add_role($role, $display_name, $capabilities);
  • $role is the name of the role that will be used by php
  • $display_name is the nice name of the role
  • $capabilities is and array of the capabilities the role has

For example:

$capabilities = array('read' => true, 'edit_posts' => true, 'delete_posts' => false);
add_role($role, $display_name, $capabilities);

will add a role to the WordPress database that can read and edit posts, but not delete them.

You can ad as many capabilities to your role as you wish. Check the WP Codex page for a complete list.

Once you have your custom role created, you can give users the role from their profile page, in the manage users page in the WordPress dashboard.

Suggestion: Try creating a role for something like Sub-Administrator that has most but not all the abilities of regular administrators. Perhaps grant them the ability to install and edit plugins, but deny them the ability to switch or install themes.



Comments (2)

  • Comment by Pippin

    You would probably have to pass the array of users through some sort of PHP sort function.

  • Comment by getinfoarticles

    Hi I am looking to sort the users according to their roles in user admin. Would like to know if this is possible in the first place. Thanks