5

I need to add a class of the user's role to my page. Ive tried the following but it doesn't work, and it seems from the comments its not working for others aswell.

function THEMENAME_preprocess_page(&$vars) {
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $vars['class'][] = 'role-' . drupal_html_class($role);
    }
  }
}

http://grasmash.com/article/drupal-add-current-users-role-body-classes

6

Use the hook_preprocess_html:

function THEMENAME_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}
| improve this answer | |
  • 1
    At the time that I stumbled upon this answer, everything worked except that I had to add the new class to $vars['attributes_array']['class'][] instead of $vars['classes_array'][]. – joe_flash Jun 18 '13 at 19:14
2

This worked for me using the Omega 3.x theme on Drupal 7. Just add it to your template.php file and it will work. Rename THEMENAME with your theme's name.

Will result in the following format:

<body class="html front logged-in page-home toolbar role-authenticated-user role-administrator">

===========

<?php
function THEMENAME_preprocess_html(&$vars) {
  $body_classes = array($vars['classes_array']);
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $role_class = 'role-' . str_replace(' ', '-', $role);
      $vars['attributes_array']['class'][] = $role_class;
    }
  }
}
?>
| improve this answer | |
0

For non-omega themes, I used duckx's approach and ended up with:

function THEMENAME_preprocess_html(&$vars) {    
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $role_class = 'role-' . str_replace(' ', '-', $role);
      $vars['classes_array'][] = $role_class;
    }
  }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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