hook_menu_links_discovered_alter() not being called I'm working on a theme for a Drupal 8.8 project. I've implemented hook_menu_links_discovered_alter() in my .theme file – but Drupal doesn't seem to be invoking it, and I don't understand why.

(For context: my goal is to make some modifications to the "Log in" and "Log out" links on the user account menu. I've found numerous examples online which say that this is the right hook to use for this purpose.)

Here's what I've tried:


I've checked (a dozen times) that I'm using the correct function name, with the correct signature: mythemename_menu_links_discovered_alter(&amp;$links)
I've added die('in hook') in my hook function to determine whether it's even being called. (It's not.)
I've cleared cache many times, from both the Drupal web dashboard and via drush cr. No luck.
I've noticed that Drupal sometimes takes a while to notice changes to .theme files, even after you've cleared cache. So, to be absolutely sure that Drupal is using the latest version of the file, I've added echo statements to other (already-working) hooks. This has confirmed that Drupal is using the latest version of the file – but mythemename_menu_links_discovered_alter() still isn't being called.


Any ideas?
Generally, alter hooks are invoked even if they are implemented in themes, but to be sure you always need to check the code invoking the specific alter hook.
In this case, hook_menu_links_discovered_alter() is invoked from MenuLinkManager::getDefinitions. You can see this by clicking on 1 invocation of hook_menu_links_discovered_alter().


  


That method only invokes the hook implemented by modules, as it uses the following code to invoke it.

  $this-&gt;moduleHandler-&gt;alter('menu_links_discovered', $definitions);


To allow themes to alter those links, the code should contain a line similar to the following one, where $this-&gt;themeManager is an object implementing the ThemeManagerInterface interface.

  $this-&gt;themeManager-&gt;alter('menu_links_discovered', $definitions);


In short, you can only implement hook_menu_links_discovered_alter() in a module.