How can I check to see if the current logged-in user is an administrator or an editor?
I know how to do each individually:
<?php if(current_user_can('editor')) { ?>
<!-- Stuff here for editors -->
<?php } ?>
<?php if(current_user_can('administrator')) { ?>
<!-- Stuff here for administrators -->
<?php } ?>
But how do I work those in together? I.e., the user is an administrator or editor?
First answer, not WordPress-related because it is just only PHP: Use the logic “OR” operator:
If you want to check more than two roles, you can check if the roles of the current user is inside an array of roles, something like:
However,
current_user_can
can be used not only with users’ role name, but also with capabilities.So, once both editors and administrators can edit pages, your life can be easier checking for those capabilities:
Have a look here for more information on capabilities.
First,
current_user_can()
should not be used to check a user’s role – it should be used to check if a user has a specific capability.Second, rather than being concerned with the user’s role but instead focusing on capabilities, you don’t have to bother with doing things like the problem asked about in the original question (which is checking if the user is an administrator OR an editor). Instead, if
current_user_can()
was being used as intended, which is to check for a user’s capabilities, not their role, you wouldn’t need the conditional check to contain an “or” (||) test. For example:if ( current_user_can( 'edit_pages' ) ) { ...
edit_pages is a capability of both administrator and editor roles, but not any lower roles such as authors. This is how
current_user_can()
was intended to be used.As @butlerblog reply stated, you should not use current_user_can to check against a role
This notice is specifically added in the PHP documentation of
has_cap
function which is called bycurrent_user_can
The CORRECT way to do this is to get the user and check the
$user->roles
, like this:Here’s some helper functions I use to do this (as sometimes i don’t want just current user):
Then you can just do this:
current_user_has_role( 'editor' );
or
current_user_has_role( array( 'editor', 'administrator' ) );
For admin
For editor
Please note that is only working if you want to check the roles of the current user, if you need to check for any other specific user, you need to use get_user_by (https://developer.wordpress.org/reference/functions/get_user_by/) or similar methods to retrieve the user you want to check
The correct answers to the above solution-question are by else programming basic:
Brief: The administrator is found, but if we push editor the administrator is as well found. So we just let the administrator pass through and identify the editor only.
Remember you should always use this code to call that above to minimize cpu code usage: