I wrote a hook like so:

function john_page_build(&$page)
  $akeys = array_keys($page['content']['system_main']['nodes']);
  print $akeys[0];

On pages with urls like http://mysite.com/page/43, it will print the node id for that page. However, on a page with url like http://mysite.co/page/43/done?sid=2, drupal gives a warning saying that $page['content']['system_main']['nodes'] does not exist.

Is there a consistent way to get the node id WITHOUT parsing the url?

3 Answers 3


Still comes through the URL indirectly, but this is the easiest way to get it: menu_get_object.

if ($node = menu_get_object()) {
 $nid = $node->nid;

Note that if there is a node, it was already loaded by the menu system anyway and this is loaded from the static cache.

Refer this discussion for more detail.


Never use arg() in d7 (by chx)! To get actual node, use menu_get_object(), on node pages this will return the complete $node object.

  • 1
    Why not use arg() in D7? Do you have a link you can share? Thx.
    – Webdrips
    Commented Oct 25, 2012 at 5:55
  • 1
    Avoid use of this function where possible, as resulting code is hard to read. In menu callback functions, attempt to use named arguments. See the explanation in menu.inc for how to construct callbacks that take arguments. When attempting to use this function to load an element from the current path, e.g. loading the node on a node page, use menu_get_object() instead. api.drupal.org/api/drupal/includes!bootstrap.inc/function/arg/7 Commented Oct 25, 2012 at 6:02

To get nid in your hook from url, you can use arg() function as below

function john_page_build(&$page)
  $nid = arg(1);
  echo $nid;
  • what if i have seo friendly urls and the node id does not appear in the address? Will arg(1) still give me the node id? Commented Oct 25, 2012 at 4:21
  • 1
    yes you will get Commented Oct 25, 2012 at 4:26
  • I just tried it. Going to the url /john/home/welcome, the echo arg(1) printed the word 'home' to the browser instead of the node id of 78 Commented Oct 25, 2012 at 4:30
  • i am able to get node id even though URL alias used, is /john/home/welcome a url alias for a node? Commented Oct 25, 2012 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.