Skip to main content
2 of 2
edited title
leymannx
  • 18.8k
  • 6
  • 72
  • 126

How to programmatically get the NID of the current node

I've pored over this old thread on drupal.org and it just kind of makes my head spin around. Pulling down the path and trying to parse out the NID from within it? There has to be a better way.

And solutions like

global $node;
$nid = $node->nid;

don't work in my custom module (though I'm told they work in templates?). No error or anything, it just instantiates $node with a NULL value.

It feels like there must be something really obvious that I'm missing.

So, how do you get the NID of the current node without a template, while following best practices and building a reasonably robust module?

beth
  • 9.1k
  • 3
  • 37
  • 86