Lee Willis

Adding body classes based on Drupal role / user ID

| 4 Comments

I’m writing this down here quickly because it strikes me that it may well come in handy to others. This little module snippet that will add classes to Drupal’s html (On the body element) to indicate the current user’s role, and user ID.

Before:

After:

Handy if for example you want to style things differently based on the user’s role. Just drop it into your module, and replace MODULE with your module name.

The code:

function MODULE_preprocess_html ( &$variables ) {

  global $user;

  foreach ( $user->roles as $role_id => $role ) {
    $variables['classes_array'][] = "role-id-".$role_id;
    $variables['classes_array'][] = "role-".strtolower(drupal_clean_css_identifier($role));
  }

  $variables['classes_array'][] = "user-uid-".$user->uid;

}

4 Comments

  1. Thank you! Works great! 🙂

  2. Also check out https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_html_class/7

    Just a wrapper for this function, but it converts alpha characters to lower case too.

  3. This worked like a charm for me. I had to hide some fields from all others that were not admins and didn’t want to get too far in the weeds with access hooks and what not.

    Used CSS.

Leave a Reply

Required fields are marked *.