There are lots of examples of seeing if the current user has a particular role. I need lightweight function to see if another user has a particular role.

For comments, I want to highlight comments from users who have a particular role, "Guest Blogger". Using hook_preprocess_comment(&$variables) I can load up each user using:

$user_fields = user_load($variables['comment']->uid);

But this seems rather heavy. All I need to do is see if the user has a role, not load up the entire user object.

Can someone help me out with a function or a query where I pass in the uid and the function/query passes back an array of roles?

1 Answer 1


Something like:

function MYMODULE_get_user_roles($uid) {
  $roles = &drupal_static(__FUNCTION__, array());

  if (!isset($roles[$uid])) {
    $query = db_select('role', 'r')
      ->fields('r', array('rid', 'name'))
      ->condition('ur.uid', $uid);

    $query->join('users_roles', 'ur', 'ur.rid = r.rid');

    $roles[$uid] = $query->execute()->fetchAllKeyed();

  return $roles[$uid];

You might want to add static caching to that if you plan to call it more than once for any single user during a single page build.

  • +1. But note that user_load() is not that bad because theme_username() probably loads the user object anyway.
    – AKS
    Feb 19, 2013 at 15:55
  • @AyeshK You'd think, but no :) The user name and uid are normalised directly into the comment/node tables, specifically to stop user_load() having to be called in those sorts of situations. theme_username() doesn't do any object loading at all, so the above query will be much quicker than user_load if the OP is just after the user roles
    – Clive
    Feb 19, 2013 at 16:02
  • Sorry I meant theme_username uses a user object to theme the username. I have overridden the theme_username a few weeks back and I had the whole $user object.
    – AKS
    Feb 19, 2013 at 16:28
  • Gotcha - you still don't need to use user_load for that though as the fields aren't nedded. A db_query('SELECT * FROM {users} WHERE uid = :uid', array(':uid' => $uid))->fetchObject(); would be much cheaper :) theme_username only accepts an account variable it doesn't instantiate it. Getting picky now though ;)
    – Clive
    Feb 19, 2013 at 16:31
  • 1
    This is a nice guide for drupal_static() lullabot.com/articles/beginners-guide-caching-data-drupal-7
    – AKS
    Feb 19, 2013 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.