Show/hide content for special users in WordPress

Sometimes you need to hide or show some content for some users with a special role. I met this problem many time on freelance. So here is simple code for the default user roles such as editor and administrator. With you using of this code you can show different content for different user roles.
<?php if( current_user_can('editor')) {  ?> 
    <!--stuff here for editors-->
<?php } ?>
<?php if( current_user_can('administrator')) { ?>
    <!--stuff here for admins-->
<?php } ?>
Another related topic to this is how to show content for multiple roles. Here is an example of code how to show content only for editors and administrator
<?php if( current_user_can('editor') || current_user_can('administrator') ) {  ?> 
    // stuff here for admins or editors
<?php } ?>
If you want to check more than two roles, you can check if the roles of current user is inside an array of roles, something like:
$user = wp_get_current_user();
$allowed_roles = array('editor', 'administrator', 'author');
<?php if( array_intersect($allowed_roles, $user->roles ) ) {  ?> 
   //stuff here for allowed roles
<?php } ?>
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 that capabilities:
<?php if( current_user_can('edit_others_pages') ) {  ?> 
    // stuff here for user roles that can edit pages: editors and administrators
<?php } ?>
Sometimes you need to show content only for members, but also different content for editors and hide content for not logged in users. Here is the script:
<?php if( current_user_can('editor')) :
  //stuff here for editors
elseif( current_user_can('member')) :
  //stuff here for members
else :
 wp_die("<h2>To view this page you must first <a href='". wp_login_url(get_permalink()) ."' title='Login'>log in</a></h2>");

Leave a Reply

Your email address will not be published. Required fields are marked *