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('/(rn?|n)/', '/\\*/', '/(^||)\\<front\\>($||)/'), array('|', '.*', '1'. preg_quote(variable_get('site_frontpage', 'node'), '/') .'2'), preg_quote($include, '/')) .')$/';
if (preg_match($regexp, $path)) {
$regexp = '/^('. preg_replace(array('/(rn?|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.

Comments
Post new comment