How To Get Access To The Current $node Object In A Drupal Block Or Elsewhere

One thing I noticed about Drupal's architecture is that it doesn't pass the current $node object everywhere you may want to use it. This has been a pain in the butt for me, and probably others who extend Drupal as much as possible with all sorts of digital duct tape.

Therefore, I spent some time and did not find anything easily obvious, or helpful in Drupal's API documentation. But I did find enough information how to get the node object in blocks for the page you are currently viewing. Here's how I did it:

Put The Node ID In A Helper Variable In hook_preprocess()

Edit or create your hook_preprocess function in your theme, and cycle trhough the $vars variable to find the node id. This is important, because (if I recall correctly) there was a problem assigning a new helper variable to a null reference:

functionhook_preprocess(&$vars){

    foreach ( $vars as $var ){

        if ( !empty( $var->nid ) ){
            $node_id = $var->nid;
        }
    }
    $vars['node_id'] = $node_id;
}

As you can see here, we verify the node id exists for this page, and then assign it to a helper variable using $vars[], which is then available across the theme files.

Load The Node From The Node Id

The next step is to then load the node variable where you need it. Now that you have the node id, you can do this from pretty much anywhere. So, if you're trying to get some current node information from a left block, you could have something like this in your block-left.tpl.php file:

<?php
    $_node = node_load( $node_id ) // Just in case,
                                   // I don't want
                                   // to piss off
                                   // Drupal by
                                   // accident, so I
                                   // use $_node
                                   // instead of $node
?>

<p>Currently viewing node id
<?php print $_node->id; ?> at about
<?php print $node->created; ?>seconds since the UNIX
Epoch!</p>
?>

Although in some cases I may designate $node in the block when loading the node object, I try to remember to use $_node, since $node is a specifically designated Drupal variable. It's a safety precaustion to avoid headaches down the road. However, this should give you access to the node object is most places you need it, except when editing PHP inside the CMS. Beware of that...