I need a function to return the nid of the current node that the current user is watching. Can you help me?


If you are insisting on a function then you are looking for arg function.

arg(0) will return 'node' and arg(1) will return node nid.

Provided you must be inside a node.

[Updated Answer]

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
    $node = node_load($nid);
    /** do something **/  


you can get nid from node object $node->nid

| improve this answer | |
  • Oh,arg is very exiting function,but how to use it?can you give me some example? – mahdi alikhasi Aug 8 '13 at 6:08
  • see my updated answer. – Ram Aug 8 '13 at 6:18
  • 1
    If you want the node object directly you can use the function menu_get_object(), it will save you a few lines of code – wranvaud Apr 11 '16 at 19:44

You can access $node object. $node->nid will return you NID of the node.

There is a hook to help you further to achieve something when user is viewing node - hook_node_view().

There are three parameter of the hook - $node (will return node object), $view_mode (view mode of the node like full or teaser) & $langcode (language code for rendering).

You can use this hook in your module & write your logic like -

function MYMODULE_node_view($node, $view_mode, $langcode){//replace your module name with MYMODULE here
  if($node->type == 'article' && $view_mode == 'full'){ //if content type is article & user is on full node view
    //do domething
| improve this answer | |
  • I think you should change || with &&.Am I right? – mahdi alikhasi Aug 8 '13 at 5:29
  • @mahdialikhasi Yeah my mistake, sorry. I have edited the code.. – RajeevK Aug 8 '13 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.