Make a Drupal Block Visible for Entire Site Sections but NOT Specific Sub-sections or Pages
This little php snippet has come to the rescue many times throughout my Drupal development days. It lets you use includes and excludes in your Drupal block visibility settings - something that you can not do out of the box.
For example, it would allow you to:
- Show this block on blog/* but not blog/somepage and blog/other page
- Show this block on news/* about/* and features/*, but not about/tom or news/listing/*
<?php
/* a list a pages to include in standard block include/exclude format (one per line) */
$include = "some/site/section/*
another/page/here
node/34";
/* a list a pages to exclude in standard block include/exclude format (one per line) */
$exclude = "some/site/section/page1
some/site/section/page2";
/* ----------- DO NOT TOUCH ANYTHING BELOW THIS LINE ----------- */
$match = FALSE;
$path = drupal_get_path_alias($_GET['q']);
$regexp = '/^('. preg_replace(array('/(\r\n?|\n)/', '/\\\\\*/', '/(^|\|)\\\\<front\\\\>($|\|)/'), array('|', '.*', '\1'. preg_quote(variable_get('site_frontpage', 'node'), '/') .'\2'), preg_quote($include, '/')) .')$/';
if (preg_match($regexp, $path)) {
$regexp = '/^('. preg_replace(array('/(\r\n?|\n)/', '/\\\\\*/', '/(^|\|)\\\\<front\\\\>($|\|)/'), array('|', '.*', '\1'. preg_quote(variable_get('site_frontpage', 'node'), '/') .'\2'), preg_quote($exclude, '/')) .')$/';
if (!preg_match($regexp, $path)) {
$match = TRUE;
}
}
return $match;
?>
To use it, simply edit your block and set the page specific visibility settings to 'Show if the following PHP code returns TRUE (PHP-mode, experts only).' and copy and paste the above code into the text area provided. Then all you need to do is edit $include and $exclude so that they reflect your desires - just put each path on a new line, just as you do with the standard Drupal block visibility settings.
For good measure I have just added this snippet to the Drupal PHP block visibility snippets handbook.
LATEST ARTICLES
TODAY'S MOST POPULAR
-
4th Sep 08
-
8th Aug 08
-
11th Jul 08
MOST POPULAR ARTICLES
RECENT COMMENTS
-
1 day 13 hours ago
-
4 days 2 hours ago
-
4 days 7 hours ago
-
4 days 13 hours ago
-
5 days 6 hours ago

Comments
29th Nov 2009, 6:00am
Thanks, very handy!
5th Dec 2009, 4:00pm
Hi Tom, Isn't that possible using the context module? jedihe
5th Dec 2009, 5:00pm
I don't think this is currently possible using the context module. Context allows you to use numerous conditions to determine the visibility of blocks (and other things). One of those conditions is the path. However, the options provided there are quite limited, and only allow you specify include paths (so you cant include blogs/* but not blogs/sompage). As far as I am aware there is no way to do what I did in this article using context, though there may well be some other way.
Pleae do enlighten me if I am wrong about that though!
Please share your thoughts, comments and suggestions...