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?


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.

| improve this answer | |

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.

| improve this answer | |
  • Why not use arg() in D7? Do you have a link you can share? Thx. – Webdrips Oct 25 '12 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 – mohit_rocks Oct 25 '12 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;
| improve this answer | |
  • 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? – John Oct 25 '12 at 4:21
  • 1
    yes you will get – Anoop Joseph Oct 25 '12 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 – John Oct 25 '12 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? – Anoop Joseph Oct 25 '12 at 4:48

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.