Drupal: Using node and user information in block code
This is for Drupal 5, don’t know if it works also in version 6.
Usually block content is not related to the currently displayed node. I.e. the block that displays the recent blog posts always displays the same content, regardless of on what page you are currently looking.
I often had situations where I wanted the block content to be related to the currently viewed node. To keep the example: When viewing a blog post, I wanted a block to display the most recent post of the author of the currently displayed post, and additionally print some profile fields like age and a gravatar.
The key to achieve this goal is the Drupal arg() function. This function returns the components of the currently viewed path before any URL aliasing. So if you view the node 5, that is yourdomain.com/node/5 (and sometimes a trailing “view”), you will get following results from function arg():
arg(0) -> "node"
arg(1) -> "5"
arg(2) -> "" or "view"
Now, if you want to get some information about node 5, you use node_load(). And to get information about the user that is the author of node 5, you use user_load().
In PHP code it works out like:
if (arg(0) == 'node'
&& is_numeric(arg(1))
&& (arg(2) == '' || arg(2) == 'view')) {
$node = node_load(arg(1));
if (is_numeric($node->uid))
$user = user_load(array('uid' => "$node->uid"));
... do something with $node and $user here
}
BTW: If you need this a lot, you should consider writing a module for your content type
To make a useful example out of it…
I use the following “debug-block” while developing to view my node and user objects:
if (arg(0) == 'node' && is_numeric(arg(1))
&& (arg(2) == '' || arg(2) == 'view')) {
$node = node_load(arg(1));
if (is_numeric($node->uid))
$user = user_load(array('uid' => "$node->uid"));
print "node object<br>";
foreach ($node as $k => $v) {
print "[$k] = $v<br>";
}
print "<br>user object<br>";
if ($user) foreach ($user as $k => $v) {
print "[$k] = $v<br>";
}
} else {
print 'not a node';
}










December 22nd, 2008 at 11:52 pm
And what if there is an url alias? How can you get the nid in a block’s code, if the nid is not in the url?
December 23rd, 2008 at 12:27 am
I got the answer: arg() works with alias too.