User roles and capabilities in WordPress are something I’ve been looking at recently for the Discussion Board and Restrictly plugins. One thing I need to check is the user’s role and whether that grants them permission to view certain content.

There’s not actually a WordPress function to give you the role of a user so it’s necessary to concoct your own. This is what I used for Restrictly when checking if a user can view a page or post:

function restrictly_get_current_user_role() {
  if( is_user_logged_in() ) {
    $user = wp_get_current_user();
    $role = ( array ) $user->roles;
    return $role[0];
  } else {
    return false;
  }
 }

First off, we check that the user is actually logged in. If they’re not logged in, they won’t have a role assigned.

If the user is logged in, we use wp_get_current_user to return the WP_User object. This provides us with a stack of information about the data and we can access their user role(s) via $user->roles. Note that I’ve cast this to an array for safety.

Then, just return the first element in the array, which will be the user’s role. If you’re expecting the user to be assigned more than one role you return the array as is.

Published by Catapult Themes

I make themes and plugins for WordPress

Leave a Reply

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