0

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(&$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?

  • This hook is not invoked for themes, you need a module. – 4k4 May 15 at 13:18
  • That would certainly explain it – thanks. Looking at the Drupal API docs, is there some way I can tell which hooks are invoked for themes, and which aren't? I don't see anything obvious. And, what's the reason that some hooks aren't available to themes? – greenie2600 May 15 at 13:23
0

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().

screenshot

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

  $this->moduleHandler->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->themeManager is an object implementing the ThemeManagerInterface interface.

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

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

| improve this answer | |

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.