Show block to certain users or roles only- Drupal 4.6

Note: Some of the examples from this section may not work with versions of Drupal older than 4.5.

Example: you want to show a block only to logged-in users. Site administrators often wish to restrict anonymous users from seeing certain (custom) blocks. Placing the following code in a PHP block will achieve this.

<?php
global $user;
if (
$user->uid) {
    return
"This block is only visible for logged-in users.";
} else {
    return;
}
?>

Replace the string "This block is only visible for logged-in users." with anything you want to display only to logged-in users.

You could also put the contents in an IF / ENDIF statement:

<?php
global $user;
if (
$user->uid): ?>

  <ol>
  <li><a href="/linky">lorem ipsum</a></li>
  <li><a href="/linky_too">lorum ipsum</a></li>
  </ol>
<?php else:
    return;
    endif;
?>

If you want a more html friendly way to display the information contained.

The block will not be shown at all for users who are not logged-in. You can replace the single return in the else-block with, e.g.,

<?php
return "This block is only visible for logged-in users.";
?>

to show some text instead of not displaying the block at all.

Example: Wrapping HTML content so it is visible only to anonymous users. This example uses an if/endif construction to wrap some HTML in a few lines of PHP which will show the content only to anonymous users.

<?php
global $user;
if (!
$user->uid) :  ?>

   <p>This content will be visible only to anonymous users.</p>
<?php else {
    return;
}
endif;
?>

4.6 Example: Showing a block only to certain users. If you want to show a certain custom block only to a certain user, you can use the following code in a PHP block:

<?php
global $user;
if (
$user->uid == 19) {
    return
"This block is only visible for the user with the user-ID 19.";
} else {
    return;
}
?>

4.6 Example:To show to specific roles only in Drupal 4.6. In this example the role is "admin user".

<?php
global $user;
$output = '';
if (
in_array('admin user',$user->roles)) {
  
$output .= '<i>A block for admin users</i>';
  
$output .= '<ul>';
  
$output .= '<li><a href=/"?q=Admin/">Administration interface</a></li>';
  
$output .= '</ul>';
}
return
$output;
?>

 
 

Drupal is a registered trademark of Dries Buytaert.