Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

How to access the node object in a custom module.

Parent Feed: 

Alright. I decided I should start sharing my answers to problems I have googled for, to save others the trouble of going through the long process of figuring things out for themselves.

First problem: I am writing a module that displays blocks, and I want to access the node object to use some variables from the page being viewed in order to use these variables to construct some of the contents of the block.

I googled “how to access the node object”, “how to load the node object”, "load node object in custom module" and so on. Could not find the answer.

The answer is extremely simple: The function menu_get_object()

$node = menu_get_object();
// Use node title as alt text and title text on a fancy gif animation.
print '' . $node->title . '';

Note that $node will be NULL if you are not on a node page, i.e a page created by some module. The function itself takes arguments for other modules, if they provide a load object. This is the function from api.drupal.org:

menu_get_object($type = 'node', $position = 1, $path = NULL)

Here is the decorative output of the code above:

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web