How to get nodeid in Drupal for the current page without using the information from the page url? I.e.:
if(arg(0)=='node' && is_numeric(arg(1))){
$nid = arg(1);
}
I do not want to use the above approach.
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.
$node = menu_get_object()
with something similar to code original question, saving 500+ database requests per page. Use with care!
Unless there is some technical reason why the arg() method is unavailable (or you NEED to check access as in other posts), the arg() method is the simplest and quickest.
If you then need additional properties you can run a node_load() to get the ID. Assuming you are trying to get the current node, this has pretty much no performance hit.
You can get the node's ID by calling $node->nid
. Indeed, getting the ID from the URL is not the best solution because you may some day switch to more SEO-friendly URLs.
From this documentation, it looks like $node
is defined in page.tpl.php
, so it should be available to you.
<?php
// In a template file...
if ($node) {
echo $node->nid;
}
else {
// you are viewing taxonomy, view, etc
}
?>
Easiest way to do this in Drupal 8:
$path_args = explode('/', current_path());
print $path_args[1];
Another pretty straight forward and reliable approach in D7 would be
<?php
if (isset($node->nid) && count($node->nid) > 0){
$nodeid = $node->nid;
}
?>
Zourtney's suggestion causes an undefined index error in my case.