0

How do I query for a specific user role?

if (is_user_logged_in() && user_role == "user") {}

The part I'm unsure about is user_role.

Is there a way I can ask WordPress to check for a specific user role by name/string?

  • Use get_user_by() with slug or user_login. It returns an object, so go through it accordingly. – Mayeenul Islam Aug 20 '15 at 9:40
  • so get_user_by('roles','13') ? 13 equals admin for example? Or can I just combine these? Because I need a role, not a specific user. So... ID -> caps? – theHubi Aug 20 '15 at 9:53
  • 1
    Then if I get you correctly, you need this: if (is_user_logged_in() && current_user_can("role_name") ) {} – Mayeenul Islam Aug 20 '15 at 10:07
1

You can check for specific user role using following code -

if (is_user_logged_in() && current_user_can('administrator')) {}

The function current_user_can() takes role name as parameter.
For more info - https://codex.wordpress.org/Function_Reference/current_user_can/

0

You can make WordPress query for a certain user role by using current_user_can("role_name").

Thanks to Mayeenul Islam for providing the solution!

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.