Getting node id inside block template with Drupal 7
Asked Answered
S

2

6

Alright, so I've created a template file for one of my blocks, which works just fine. However inside this template I would like to get the id of the current node. How is that possible? I've tried arg, $node and all of these variables, but none of them are available.

Thanks in advance.

Slone answered 31/1, 2012 at 14:47 Comment(1)
I love you for asking this question! ;)Pitzer
D
23

Assuming you're on the node page itself the menu_get_object() function will return the node object:

$node = menu_get_object();
if ($node && $node->nid) {
  // You have a valid node to work with.
}
Dub answered 31/1, 2012 at 15:45 Comment(3)
Unfortunately, that is not a safe assumption.Mistreat
@Mistreat For the phrase "current node" it's a safe assumption (that's what that phrase refers to in Drupal-eze). If it's a not a node page what "current node" are you looking for? There's likely to be a similarly easy method to find itDub
On second read, yes, I suppose you are right. I read 'current node' as the node for the current block.Mistreat
S
0
// it will gives only node id.
if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
}
echo $nid;
Specific answered 18/7, 2017 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.