4

In my main menu I have a "menu item 1" that links to mynode1.

I have successfully implemented hook_permission() and hook_node_access() so that users who do not have the "access menu item 1" permission cannot access mynode1.

I assumed that the menu item link "menu item 1" would automatically be hidden by Drupal, but this is not the case. Therefore I now would like to hide that menu item to users who do not have "access menu item 1" permission.

Does anyone have a code sample that would hide a menu link based on permission? (I tried hook_menu_alter() with no luck.)

  • Its drupal default behaviour as I remember.. – RajeevK Aug 10 '13 at 17:14
  • If you hide a link, it doesn't mean that user won't be able to visit that content. You need to use hook_node_access and here you have a good example. – Jack-PL Aug 10 '13 at 23:09
1

Hi have done it this way:

function mymodule_menu_link_alter(&$item) 
 {
  $item['options']['alter'] = TRUE;                                                                                                                                                      
 } 

function mymodule_translated_menu_link_alter(&$item, $map) 
 {

  if (!empty($item['access'])) {

  if(
   ( $item['link_title']=="MyLinkToHide1" && !user_access("access link 1") ) ||
   ( $item['link_title']=="MyLinkToHide2" && !user_access("access link 2") )

   )
   {
            $item['access'] = FALSE;
   }

 }
}
  • There actually is a better way here : "It seems that a better way to control node access through hook_node_access_records and hook_node_grants as described here". – Baba Oct 25 '13 at 17:13
0

I think the best way to hide the menu items according to permissions is to use hook_menu_link_alter and set $item['hidden'] = 1; if user_access returns false.

Resources

  1. user_access
  2. hook_menu_link_alter
0

There is the Menu item visibility module.

This module exposes configurable and extendable visibility settings for menu links. For example, if you want to create a 'My account' link that points to /user, both anonymous and registered users have access to the /user path, so both will see the link, even if anonymous users do not technically have an account. Using this module will allow you to only have your 'My account' link visible to registered users, and hide it from anonymous users.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.