How to check if current user is administrator or editor in WordPress

--

WordPress has a build in function to check if the current logged-in user is whether administrator, editor or any other role you have. I am talking about the current_user_can() function and WordPress capabilities. This function returns whether the current user has the specified capability.

This is very useful in cases you want to show content to a user with specific role. I personally use this every time I want to test something new like a design, copy, image, behavior, user experience, process and so on. I just wrap the desired test change in this simple code. Use it in your child’s theme functions.php or directly in template files.

<?php if(current_user_can(‘administrator’)) { ?>
<! — Stuff here to show only to administrators →
<?php } ?>

Here are some other roles you can check for:

<?php
if( current_user_can( ‘administrator’ ) ){} // only if administrator
if( current_user_can( ‘editor’ ) ){} // only if editor
if( current_user_can( ‘author’ ) ){} // only if author
if( current_user_can( ‘contributor’ ) ){} // only if contributor
if( current_user_can( ‘subscriber’ ) ){} // only if subscriber
?>

If you want to check for either two or more roles at the same time, just combine the functions as such:

<?php
if( current_user_can( ‘administrator’ ) || current_user_can( ‘editor’ ) ){
// Your code here
}
?>

The article was originally published on webroom.tech

--

--

webroomtech.com
webroomtech.com

Written by webroomtech.com

0 Followers

webroom.tech is created and written with one purpose: to help anyone developing their awesome WordPress and WooCommerce website.

No responses yet