Hook_Menu Access Callback to Restrict by User Role

When defining an "access callback" for a menu item in hook_menu, Drupal doesn't provide a callback for restricting access by a user's role. Which seems to be a bit of an oversight. So here's some code run a simple check against the user's role:

 

hook_menu function
function example_menu() {  
  $items['example/%user'] = array(
    'title' => 'My Page',      
    'page callback' => 'example_custom_page',    
    'access callback' => 'example_user_has_role',   
    'access arguments' => array(1, array('my-role')), // arg 1 loads the user, arg 2 is the role name
    'type' => MENU_NORMAL_ITEM,
  ); 
 
  return $items;
}

 

custom access function
function example_user_has_role($user, $roles = array()) {  
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE; 
}

 

If your path can't use the %user wildcard argument, you can write a custom access callback that just checks the roles of the current logged in user (via gobal $user).