Show a block depending on node type and node id
The following snippet allows you to configure certain blocks to show only when the user is at a specific node type and with a specific node id. You can modify the arrays in the snippet to match your needs. Just modify and paste this snippet on the block
How to use:
1. Go to your blocks administer section "Home » Administer » Site building".
2. Add a new block "Add block". (If not just "configure" the one you already have.).
3. Go to "Page specific visibility settings".
4. Select "Show if the following PHP code returns TRUE (PHP-mode, experts only).".
5. Paste the snippet in the text area just below. (NOTE: Remember to keep the <?php> tags.)
Modifying Arrays:
Node Type Array
$types = array('page' => 1);
Node ID Array
$nodes = array(1, 2);
The following will show the configured block in:
Example: http://www.yoursite.com/node/1
Example: http://www.yoursite.com/node/2
<?php
// Only show block from types array and nodes array
$match = FALSE;
// Which node types
$types = array('page' => 1);
// Which nodes (by nid)
$nodes = array(1, 2);
if (arg(0) == 'node' && is_numeric(arg(1))) {
$nid = arg(1);
$node = node_load(array('nid' => $nid));
$type = $node->type;
if (isset($types[$type]) && in_array($nid, $nodes)) {
$match = TRUE;
}
}
return $match;
?>
How would you limit to node
How would you limit to node type only and not node ID? I tried removing the node ID parts but then nothing displayed.
What do I need to remove to just limit to node type?
Thanks!
This seems to work for me
<?php
// Only show block from types array and nodes array
$match = FALSE;
// Which node types
$types = array('area' => 1);
if (arg(0) == 'node' && is_numeric(arg(1))) {
$node = node_load(array('nid' => $nid));
$type = $node->type;
// arg(2) to stop displaying on edit etc
if (isset($types[$type]) && arg(2) ==null) {
$match = TRUE;
}
}
return $match;
?>
An other variation
Using the same concept and with a bit of code clean-up, this it what I used to show only on specified node types:
<?php
// Only show if $match is true
$match = false;
// Which node types
$types = array('book', 'news', 'anothernodetype' );
// Match current node type with array of types
if (arg(0) == 'node' && is_numeric(arg(1))) {
$nid = arg(1);
$node = node_load(array('nid' => $nid));
$type = $node->type;
$match |= in_array($type, $types);
}
return $match;
?>