2

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

0

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.

1
  • Thank you for your answer. I've voted up, but can't cast vote, until my reputation goes 15. :(
    – Abirvab
    Nov 25, 2015 at 5:00
0

Create a capability for managing the plugin. Admins by default have it and they can use any of the role/capability management plugins to add it to roles or users. Just be explicit about it in your documentation.

You can actually add it in your UI (let the admin select the role and add the capability to it) but you should think if it will just become a UI bloat which is not going to be used by most people.

1
  • 1
    Thank you for your answer. I've voted up, but can't cast vote, until my reputation goes 15. :(
    – Abirvab
    Nov 25, 2015 at 5:00

Your Answer

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

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