I have a block that I only want to display in nodes that the current user created. What's the best way of going about this?
Thoughts so far
I can access $user
(and therefore the UID) anywhere, so I need to compare this to the node author UID. The only problem is finding a place where I can also pull in the current node information to find out it's author.
I really don't want to put php in a block (bad practice and all) and I couldn't see where I'd do this in context.
If I can't find a better way then the backup plan is to create an automatic field on node creation which contains the authors UID, then use this in page.tpl.php to set a class which will apply display:node to the block whenever the author UID =! user UID.
EDIT: Solution
The block I was trying to effect was in a custom module, so I took Yuriy's code and put into the modules hook_block_view. The result was this:
function mymodulename_block_view($delta = '') {
$block = array();
switch($delta) {
case 'mymodulename_form':
if (preg_match('#node/([0-9]+)#', $_GET['q'], $matches)) {
if ($node = node_load($matches[1])) {
global $user;
if ($user->uid !== $node->uid) {
$block['content'] = array();
} else {
$block['content'] = drupal_get_form('mymodulename_form');
}
}
}
break;
}
return $block;
}
I think this is what's going on:
preg_match
and $_GET are used to take the node path from the current page. This returns: "node/xx". This is then used to load the correct node which is then matched against the global UID. An if
function then either empties the block content or fills it.