6

In Drupal 6, to check if current page is a node, we use the following snippet:

if (arg(0)=='node' && is_numeric(arg(1))) { /* Do stuff. */ }

Since this is a frequently used statement, I wonder if there's a shorter way to do this in Drupal 7, such as something similar to the following:

if (is_node()) { /* Do stuff. */ }
15

Actually, there is a function that is available in Drupal 6 too: menu_get_object(). With the default values, it will return a node object if the URL for the current page starts with node/[node ID] (where [node ID] is the node ID), and FALSE in the other cases; the function is particularly useful if, after verifying the current page is a node page, you also need to access the node object associated with the page, and the function that is calling menu_get_object() doesn't get a node object between its arguments.

In Drupal 7, there is also another function, but its purpose is just to verify if the current viewed page is the full page view of the node passed as argument: node_is_page().

  • That's not strictly true, though, right? If you call menu_get_object on a taxonomy listing page, or a view, it will still return an object, but that object will not be a node. I think maybe arg(0) === 'node' works instead? – cam8001 Jun 1 '18 at 23:42
  • No, menu_get_object() returns an object only when the user is viewing a node page, since its first parameter has the default value of 'node', otherwise it returns FALSE. With arg(0) == 'node' you cannot know if the user is editing a node. – kiamlaluno Jun 2 '18 at 8:56

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.