How can I allow user to select minimum privilege smartly

We can easily asses a user’s role using current_user_can(), but it doesn’t support an array of user roles but a single role. So we have to check each of the role multiple times:

if( current_user_can('administrator') || current_user_can('editor') ) {
  //do this
}

I’m making a WordPress Plugin, I need the administrator should choose the minimum privilege to administer the plugin. If the roles are hierarchical then they are like so (for single site):

  • Administrator
  • Editor
  • Author
  • Contributor
  • Subscriber

If the admin choose author, then I have to do 3 OR checks as shown above (if x || y || z).

Is there any smart way I can choose for this purpose so that I can let them choose the minimum privilege but I can handle it smartly too.

Thank you.

2 Answers
2

You are using the right WP function but unfortunately not passing the right parameter to make this work for you.

current_user_can() accepts capabilities as well as roles as parameters.

In the above you are using roles and not capabilities.

You can use capabilities to make it work.

For example, if you want the minimum privilege role is author your code would look like

if ( current_user_can( 'edit_published_posts' ) ) {
  //do this
}

This will allow all the roles including author to have the privilege and would stop users with roles contributor and subscriber from the access.

You can read the details of roles and capabilities from the codex here.

Leave a Comment