WordPress has a build in function to check if the current logged-in user is whether administrator, editor or any other capability 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.

When you install fresh copy of WordPress, there will be five default user roles:

  1. Administrator
  2. Editor
  3. Author
  4. Contributor
  5. Subscriber

This is very useful in cases you want to show content to a user with specific capability. 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 theme’s functions.php or directly in template files.

PHP snippet for current_user_can(): Check if user is administrator

<?php if(current_user_can('administrator')) { ?>
    <!-- Stuff here to show only to administrators -->
<?php } ?>

PHP snippet: How to check for all WordPress capabilities:

<?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
?>

Sometimes you might want to add content or display something to several user roles. You just need to use PHP logical operators to perform the check for two or more capabilities:

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

Learn more about PHP logical operators.

Learn more at the WordPress Codex.

Need help with WordPress or WooCommerce?

Visit our Community Forums

Ask a Question

Recent Articles

From Our Community Forums

Blog Categories

Related Articles

If you enjoyed reading this, then please explore our other articles below:

Comments

Leave a comment

Leave a Reply

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.