[Drupal] How to set a menu link that redirects users to different pages based on their roles
In one of our Drupal 7 sites, recently, we came across a situation where we wanted to set a menu link that redirects users to different pages based on their roles. Usually, we create separate menu items for each user and apply permissions based on their roles. However,since we wanted to avoid redundant menu items and didn't want to duplicate an entire menu branch for a shared parent menu item, we decided to set single menu item with different pointing locations.
Here is how we achieved it.
Create a menu item in your custom module
/**
* Implementation of hook_menu().
*/
function module_ads_menu() {
$items = array();
$items['ads-redirection'] = array(
'title' => 'Redirect ',
'page callback' => 'ads_redirect',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
Step 2: Set redirections based on roles
/**
* Redirect users to different pages based on their roles
*/
function module_ads_redirect() {
global $user;
if (in_array('banner ad manager', $user->roles)) {
drupal_goto('manage-banners');
}
elseif (in_array('classifieds ad manager', $user->roles)) {
drupal_goto('manage-classifieds');
}
}
Step 3: Configure the menu link
Now, create a menu link with the menu item created in step 1 and save.
- Set path as 'ads-redirection'
- Set proper visibility permissions for both 'banner ad manager' role and 'classifieds ad manager' role
Step 4: Clear menu cache
Once you clear the cache, just check and verify if this works fine.
Hope this helps.