Hi,

I want to access the node id variable within a phptemplate function. What is a function that can retrieve the node id?

thanks,
pat

Comments

nevets’s picture

When viewing a single node (url ending in node/{nid}) $node is available in page.tpl.php so you can use $node->nid.

patoshi’s picture

how would i access $node-nid if i was in a function in template.php

clemens.tolboom’s picture

The variable $node is available. You could do a print_r( $node) in ie page.tpl.php to see what's available.

dquakenbush’s picture

I'm in the same boat -- I need to read parameters of $node from within template.php (not page.tpl.php or node.tpl.php or block.tpl.php). Specifically, I need the $node->type string BEFORE we get to the page or node level theming stuff so I can meddle with menu_set_location in a meaningful way.

Is there a specific reason this isn't allowed, or even possible (has $node been instantiated by this point)?

nevets’s picture

$node is not a true global with page.tpl,php or node.tpl.php so it only has scope with that context. If you are overriding a theme function you will want to add

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

to your function. Two things to note, since the node has already been loaded, the call to node_load returns a "cached" copy of the node and $node will not always be set (not all pages are about viewing a single node).

patoshi’s picture

what were looking for is this. (its quite simple actually. I didnt even realize.) if you look at the URL and see the arguments at the end. We can grab them like this within our php files:

http://www.____.com/?q=node/123/var1/var2

arg(0) = node
arg(1) = 123
arg(2) = var1
arg(3) = var2

ashish_kataria’s picture

You can get node id in template.php file through print $_GET['q']; i.e. store the value of $_GET['q'] in variable and then extract the node id using php substr function substr($_GET['q'],5).

nevets’s picture

Using the arg() function is a much cleaner solution as you do not need to know/worry about the lengths of the various parts of the path.

ashish_kataria’s picture

Yes arg() function is a much cleaner solution but if somebody want's full path i.e. node/node-id where node-id is the node id of the corresponding page then $_GET['q'] can give you at once.And I told about this option only to have users to know about the other way around to get node id.