I’m trying to run an if statement in my wordpress functions with the current_user_can function although I’m not sure how to have it accept multiple roles. How I have it now is with just one role, but I would like to add the author role to the if statement too.
if ( current_user_can( 'contributor') ) {
// Do this
}
What I would like to do is set this up to check if they are a contributor or an author although I’m not sure how to add author into that aswell.
I tried using an array but that doesn’t seem to work
if ( current_user_can( array('contributor', 'author') ) ) {
// Do this
}
When I try the array I get an error. I’m not really sure the direction I should be going.
Thank you.
The
current_user_can
function takes a capability not a role.In this case, you find a capability that can be done by the lowest level role you wish to be able to perform this action, and pass this. All higher level roles have this capability too, so will also be able to perform this action.
In your case, try
if ( current_user_can( 'edit_posts') ) {
Please be very careful when using this function in conjunction with the admin_init hook. If you are using ajax in the front end, do not forget to check if ajax is being used ( ! defined( ‘DOING_AJAX’ ) || ! DOING_AJAX ) ), or ajax call to /wp-admin/admin-ajax.php will be blocked. https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init
See example below