Get the page node in hook_page_alter in Drupal 7

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 ...
  }
}
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter

Comment | Trackback

, ,
Code

One Response to “Get the page node in hook_page_alter in Drupal 7”

  1. Elliot Grant Says:

    December 23rd, 2011 at 9:29 am

    Thank you! That’s brilliant, and a life-saver. Now I can move content fields around to different regions. I was tearing my hair out trying to figure out how to pass $node to $page.

Leave a Reply