Skip to main content

Drupal 8: Alter a menu item title

In order to alter a menu item that is provided by a module/system, you can use hook_preprocess_menu__MENUNAME() (Since hook_menu_alter() no longer exists).

In my instance, I need to change the system provided 'Logout' link to read 'Log Out'. In order to do this I added the following to my THEMENAME.theme file:

  1. /**
  2.  * Implements hook_preprocess_menu().
  3.  */
  4. function MYTHEME_preprocess_menu__account(&$variables) {
  5.   if (isset($variables['items']['user.logout']['title']) && $variables['items']['user.logout']['title'] == 'Logout') {
  6.     $variables['items']['user.page']['title'] = 'Log Out';
  7.   }
  8. }

Deleting a menu item

Likewise, if you want to delete a menu item you can unset the item.

  1. /**
  2.  * Implements hook_preprocess_menu().
  3.  */
  4. function MYTHEME_preprocess_menu__account(&$variables) {
  5.   // Remove a menu item if the user is logged in.
  6.   if (isset($variables['items']['menu_link_content:b32ab12d-59ac-488d-a4ba-da0d70943a3f']) && \Drupal::currentUser()->isAuthenticated()) {
  7.     unset($variables['items']['menu_link_content:b32ab12d-59ac-488d-a4ba-da0d70943a3f']);
  8.   }
  9. }


Comments