Drupal: Add body classes based on user permissions

This one is a little bit more esoteric. I found the need change the page style (via CSS) based on whether the current user had permission to update the current node. Drupal preprocess_page to the rescue!

Just add this snippet to the yourTheme_preprocess_page function in your template.php file. It will add body classes (e.g., user-node-update, user-node-delete) to your page depending on the current user's permission to access the node being viewed.

<?php
function grasmash_preprocess_page(&$vars, $hook) {
  $body_classes = array($vars['body_classes']);

  //if this page is a node and we can access the user object
  if ($vars['node']->nid != "" && $vars['user']) {
    $node_actions = array('update','delete','create'); //leaving out 'view' since user can obviously view this node

    //check current user's access to this node, add body_classes accordingly
    foreach ($node_actions as $node_action) {
      if (node_access($node_action, $vars['node'], $vars['user'])){
        $body_classes[] = 'user-node-' . $node_action; //add an appropriate body class
      }
    }
  }

  $vars['body_classes'] = implode(' ', $body_classes); // Concatenate with spaces
}
?>

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.