(Tutorial) Controlling block visibility with PHP
Tutorial : Controlling block visibility with PHP
- Go to administer >> access control and ensure “administer blocks “ and “use PHP for block visibility” are checked for your role.
- Go to administer >> blocks and find the block you want to set the visibility for.
- Click “configure” next to that block.
- Under the section entitled, “Page specific visibility settings”, click the radio button for “Show if the following PHP code returns TRUE”
- In the text box provided, enter whichever of the following snippets meets your needs:
Show block only to logged in users:
global $user;
if ($user->uid){
return TRUE;
} else {
return FALSE;
}
?>Variation: “if (!$user->uid){“ will show block only to anonymous users.
Show block only to a particular role:
global $user;
if (in_array('Approved Role',$user->roles)) {
return TRUE;
} else {
return FALSE;
}
?>
Variations: Replace "Approved Role" with whichever role you want to view it. Or use !in_array to hide it for that role.Show block only to a particular user:
global $user;
if ($user->uid == 1){
return TRUE;
} else {
return FALSE;
}
?>Variations: Replace the “1” with any UID.
Show block only for specific content type:
$match = FALSE;
$types = array('story' => 1, 'page' => 1);
if (arg(0) == 'node' && is_numeric(arg(1))) {
$nid = arg(1);
$node = node_load(array('nid' => $nid));
$type = $node->type;
if (isset($types[$type])) {
$match = TRUE;
}
}
return $match;
?>Variations: This example would show the block on all 'story' and 'page' type nodes. Just change line 2 - the $types array - to indicate which node types you want your block to appear on. Use the format 'nodetype' => 1 for each type you need. And yes, the array can hold single type only.
Courtesy : Drupal1.kiev1.org
- guru's blog
- Login to post comments
![Drupal-6-Book-[Building Powerful and Robust Websites with Drupal 6].jpg](http://www.drupalranch.com/images/Drupal-6-Book-[Building%20Powerful%20and%20Robust%20Websites%20with%20Drupal%206].jpg)