How to create custom node background color from role id
e.g. admin - red
manager -green
auth user - blue, automatically?

Find examples (template.php)

function themename_preprocess_node($variables) {
  $account = user_load($variables['user']->uid);
  //$account = user_load(array('uid' => $node->uid));
  $user_roles = $account->roles;
  if (in_array('administrator', $user_roles)) {
    $my_class = 'user-admin';
  elseif (in_array('authenticated user', $user_roles)) {
    $my_class = 'user-author';
  elseif (in_array('test user remove', $user_roles)) {
    $my_class = 'user-power-author';
  elseif (in_array('VIP', $user_roles)) {
    $my_class = 'vip-author';
  if (isset($my_class)) {
    $variables['attributes_array']['class'][] = $my_class;

This doesn't work

  • background color for the <body> tag or any other div ? – GoodSp33d Sep 4 '12 at 16:50
  • Current user's role or Author's role ? – AKS Sep 4 '12 at 16:59
  • I find example: – polatay Sep 4 '12 at 16:59

UPDATE From the code you've added it looks like you want to add the class based on the node author. You can use much the same principle:

function MYTHEME_preprocess_node(&$vars) {
  $account = user_load($vars['node']->uid);

  foreach ($account->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));

Each node will have the role-rolename classes added to it (see original answer below).


Quick and easy way:

function MYTHEME_preprocess_html(&$vars) {
  global $user;

  // Loop over the user's roles and add a class to the body class array.
  foreach ($user->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));

That adds classes like role-administrator and role-authenticated-user (and any other roles the user has) to the <body> tag. From there you should be able to target things easily with CSS (e.g. body.role-manager{background:red}).

Remember to clear Drupal's caches after you've added the preprocess function, or the changes won't get picked up.

  • Perfectly. Everything works. Once again many thanks. – polatay Sep 4 '12 at 18:16

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.