I've got two roles in my website and I'd like to print the role name in the user profile page body classes for the user being viewed. How can I do this?


The html.tpl.php template uses the $classes variable to add classes to the body element. You can use template_preprocess_html() to add classes to this variable. Add this function to your theme's template.php

//Replace MYTHEME with the name of your theme
function MYTHEME_preprocess_html(&$variables) {

  //Check if the path is a profile page with a valid user
  if(preg_match('/^user\/(\d+)/', current_path(), $matches) == 1) {
    if($user = user_load($matches[1])) {

      //Add each role to the $classes_array which makes it available in $classes
      foreach($user->roles as $rid => $role) {
        $variables['classes_array'][] = str_replace(' ', '-', $role);
  • Hi Shawn thanks for your help. Maybe I've to edit the question. What I meant is: not to get the current logged in user role, but to get the role of the profile page user I'm visiting. I.e. if I see a user profile page with role-A I would like to have in the body classes user-role-a, and so on. – Emanuele Nov 12 '15 at 10:18
  • I'm trying with this code in the preprocess_html function but without success: if (arg(0) == 'user' && is_numeric(arg(1))) { $user = user_load((int) arg(1)); if (in_array('role-a', $user->roles)) { $vars['classes_array'][] = 'user-role-a'; } if (in_array('role-b', $user->roles)) { $vars['classes_array'][] = 'user-role-b'; } } – Emanuele Nov 12 '15 at 10:19
  • All that's need is a simple mod that makes $user refer to the currently viewed user. See above. – Shawn Conn Nov 12 '15 at 19:11
  • Sorry for my inexperience. Works perfectly... Thank you! – Emanuele Nov 13 '15 at 8:39

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.