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():
/**
* Implements hook_menu_link_alter().
*/
function MODULE_menu_link_alter(&$item) {
if ($item['menu_name'] == 'main-menu' && $item['link_path'] == 'path/to/my/page') {
$item['options']['alter'] = TRUE;
}
}
By setting the options=>alter to true, it signals Drupal to alter this menu with hook_translated_menu_link_alter().
/**
* Implements hook_translated_menu_link_alter().
*/
function MODULE_translated_menu_link_alter(&$item, $map) {
if ($item['menu_name'] == 'main-menu' && $item['link_path'] == 'path/to/my/page') {
if (!custom_access_function()) {
$item['access'] = FALSE;
}
}
}
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…