Display Content for a Specific Role - Drupal
Sometimes, is can be a requirement to only allowed a specific group of users to view some content on a page. I'm not talking about showing or hiding the entire page to a specific role.
What I am talking about is that an authenticated user sees some different or additional content than an anonymous user will see on the same page.
I recently had a requirement to do just this on a community website that I am building. I needed to show a discount Coupon Code to registered users but not to anonymous users.
This is easily achieved by changing the content type to PHP and inserting the following snippet of code.
<?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>Use Coupon Code: <strong>My Code</strong></p>When <a href="http://www.example.com">Ordering Products</a>';
}
else {
print '<p><a href="/user/login?destination=current-page-url">Login</a> | <a href="/user/register">Register</a><br /> To get Coupon Code.</p>';
}}
?>Just a few things to note about the about PHP snippet.
- This allows users in the "super user" and "authenticated user" groups to see the coupon code.
- Anonymous users are prompted to Register or login to see the Coupon Code.
- The "current-page-url" should be replaced with the url of the current page. This will allow a registered user to redirect straight back to the same page after logging in.
Latest Articles
About Us
NZ Web Hosting Internet Technolgies Blog.
Website design, website development, promotion and search engine optimisation.











