3

I am looking to hide a menu item based on the path of a couples pages. It would be similar to how blocks can be shown on or not shown on a path. My initial attempts revealed that the caching of menus does not permit one to have the ability to remove menu items per page load.

hook_menu_alter() only runs once after a cache clear and then the menu is retrieved from the cache. Does anyone have any ideas on how to accomplish this or is it a futile attempt?

Thanks.

4

Yes you can by using an access callback which when defined calls a function. In this function you can analyze the path and based on that return TRUE or FALSE. When you return FALSE, the menu item is not visible. See the documentation of hook_menu for more details.

A simple example:

// in hook_menu something like this, important part is the 'access callback'
 $items["menu/item"] = array(
     'title' => "menu item 1",
     'description' => 'Access test',
     'page callback' => 'node/1',
     'access callback' => 'check_path',
     'menu_name' => 'navigation',
     'type' => MENU_NORMAL_ITEM,
 );

// then define your access callback function
  function check_path(){
    // check path here and return TRUE or FALSE
    return TRUE;
  }

I just asked a similar question dealing with this: How to build a dynamic menu structure. You may find more information in that question that can help you.

  • Just sat down to try this out and realized before trying anything that this would work if I defined the menu path in a module. The catch here is that the menu item exists already. I need to modify an existing menu item to so I should use hook_menu_alter() and add a custom access callback that way. – Jepedo Oct 31 '11 at 15:24
  • Completely correct, I forgot to mention that. Beware that hook_menu_alter() is only called with a menu rebuild though. – Whiskey Oct 31 '11 at 19:56
0

Also worth mentioning there is the module path access. Here you can restrict paths by role, in a nice administrator interface. I have used this on several sites.

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.