Buy One Domain Name, Get One Free

Looking for a reliable and affordable Domain Name Registrar? Look no further than Dotster. And for a limited time, we're able to offer our visitors a buy one domain name, get one free promotion. Click here to take advantage of this offer.

Get Your Own Toll Free 800 Number

It's easy to setup your own toll free number for as little as $2/ month. Try Kall8 today and get your 800 number. Features include call forwarding, voice mail and fax, caller ID, email notifications, VoIP, and more.



Sep 15 2007

Drupal - Display Content Sections for Specific Roles Only


Filed under: Content Management Systems » Drupal,
Tools:


How do display content for specific roles only?

Drupal 5.x contains the ability to specify which roles can see specified blocks (Drupal 4.7.x did not contain this feature).  But what if you want to display sections of nodes or other content types to certain roles only?  You can use PHP to define which roles see the content, all the way down to sections of a page (as opposed to controlling the entire page).  The Drupal module nodeaccess will allow you to control node access based on user roles for entire nodes only.  Note:  failing to correctly implement PHP code can cause the node to not load at all - proceed with caution.

Using PHP to control access to entire nodes

Use the following code to control access to an entire node based on user role:

 
<?php
global $user;
$approved_roles = array('authenticated user', 'super user');

if (is_array($user->roles)) {
  if (
count(array_intersect($user->roles, $approved_roles)) > 0) {
    return
TRUE;
  } else {
    return
FALSE;
}}
?>

Using PHP to maintain user control over node sections

Use the following code around content snippets you wish to be viewed only by certain users:

 
<?php
global $user;
$approved_roles = array('authenticated user', 'super user');

if (is_array($user->roles)) {
  if (
count(array_intersect($user->roles, $approved_roles)) > 0) {
    print
'<p>Access controlled content</p>';
  } else {
    return
FALSE;
}}
?>

You could also provide a login link to encourage users to sign up to view particular content:

 
<?php
global $user;
$approved_roles = array('authenticated user', 'super user');

if (is_array($user->roles)) {
  if (
count(array_intersect($user->roles, $approved_roles)) > 0) {
    print
'<p>Access controlled content</p>';
  } else {
    print
'<p>Please <a href="/user/register">register</a> to view this content.</p>';
}}
?>

Average: 4.9 (7 votes)
Tools:



  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p> <br> <br />
  • Lines and paragraphs break automatically.
  • Textual smileys will be replaced with graphical ones.

More information about formatting options

CAPTCHA
This question is used to make sure you are a human visitor and to prevent spam submissions.