Archive for September, 2011

Get the page node in hook_page_alter in Drupal 7

Tuesday, September 20th, 2011

Many times, you need to access the node in hook_page_alter(). Traversing gets ugly, so I moved it out into this little helper.

1
2
3
function _get_page_node($page) {
 return (isset($page['content']['system_main']['nodes'])) ?  $page['content']['system_main']['nodes'][array_shift(array_keys($page['content']['system_main']['nodes']))]["#node"] : false;
}

Drop this is template.php, and now you can do something like

1
2
3
4
5
6
function YOURTHEME_page_alter(&$page) {
  $node = _get_page_node($page);
  if($node && $node->type == "article") {
    // ... edit only article nodes ...
  }
}

Tags: , ,
Posted in Code | 1 Comment »