Drupal - How to programmatically get the NID of the current node

Assuming your code is running for a node page, the methods I see used most often in core/contrib modules are either using menu_get_object() or arg():

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

or

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

I personally prefer the first method (even though assignment in condition isn't considered a good idea by some people), but both are perfectly valid.


Easiest way to do this in Drupal 8 since arg() no longer works:

$path_args = explode('/', current_path());
print $path_args[1];

Change record


arg(0) returns 'node' and arg(1) returns node nid.

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
}

Tags:

Nodes