(Tutorial) Controlling block visibility with PHP

Tutorial : Controlling block visibility with PHP

  1. Go to administer >> access control and ensure “administer blocks “ and “use PHP for block visibility” are checked for your role.
  2. Go to administer >> blocks and find the block you want to set the visibility for.
  3. Click “configure” next to that block.
  4. Under the section entitled, “Page specific visibility settings”, click the radio button for “Show if the following PHP code returns TRUE”
  5. 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.

| Read more..

Courtesy : Drupal1.kiev1.org