Skip to main content

Programmatically alter a Drupal menu without disabling access to the page.

I came across a need to keep a menu link active, but, I didn't want it to be displayed to the anonymous user. After much searching I found the hook_menu_link_alter() function and the hook_translated_menu_link_alter() function.

With these functions, I was able to alter the menu item that I wanted to not display with hook_menu_link_alter():

  1. /**
  2.  * Implements hook_menu_link_alter().
  3.  */
  4. function MODULE_menu_link_alter(&$item) {
  5.   if ($item['menu_name'] == 'main-menu' && $item['link_path'] == 'path/to/my/page') {
  6.     $item['options']['alter'] = TRUE;
  7.   }
  8. }

By setting the options=>alter to true, it signals Drupal to alter this menu with hook_translated_menu_link_alter().

  1. /**
  2.  * Implements hook_translated_menu_link_alter().
  3.  */
  4. function MODULE_translated_menu_link_alter(&$item, $map) {
  5.   if ($item['menu_name'] == 'main-menu' && $item['link_path'] == 'path/to/my/page') {
  6.     if (!custom_access_function()) {
  7.       $item['access'] = FALSE;
  8.     }
  9.   }
  10. }

This allows the path to remain active for the anonymous user, but removes the menu item from the menu completely.

Note, the hook_menu_link_alter() only runs when the menu item is saved.

References:
- https://www.drupal.org/node/1897326#comment-9034011
- https://api.drupal.org/api/drupal/modules!system!system.api.php/functio…
- https://api.drupal.org/api/drupal/modules!system!system.api.php/functio…


Comments