Drupalwoo ☉

Alter Drupal menu links dynamically with a hook

Menu links in Drupal are often configured once but need to reflect the content they point to. A case-file link might show an active status, a support link might use a different destination, and an administration item should disappear for users without the right permission. Treating every label as permanent HTML makes those decisions awkward and easy to duplicate across menus. Drupal’s menu tree, however, is built from route information and is a natural place to apply contextual logic.

Writing a Drupal hook to alter menu links dynamically means implementing hook_menu_link_alter() in a custom module. Drupal invokes it while preparing each menu link, before the render array becomes HTML. The hook receives link data by reference, the internal router path and the original route map. It can change a link title, URL, attributes or visibility while leaving the menu structure in the site editor. It applies to links rendered through Drupal’s menu system, not every anchor in a block, breadcrumb or Views result.

Why menus need dynamic link data

A configured Drupal menu is not simply a list of labels. Each item is connected to a route, and the route supplies parameters, permissions and generated URLs. That makes the menu a good place for small contextual changes: show the current workflow state in a title, redirect a general link to a personalised dashboard, or suppress an item whose target entity is unavailable.

The hook is also more focused than changing the rendered HTML after the fact. It works before theme output, so link text, destination and attributes remain coherent for screen readers, keyboard navigation and caching. It can modify existing items, although it does not create a completely new menu entry or change the menu’s hierarchy.

Compare values carefully. $router_path is an internal route pattern such as node/%node, not an alias such as /projects/case-42, and it is not automatically the path of the current page. Australian teams often scope Drupal work as a “site build” and call the primary navigation “the nav”, but the implementation should still use Drupal’s precise terms: router path, route map, menu tree and link title.

Create the hook implementation

Create a small custom module rather than editing Drupal core. For Drupal 10 and 11, place it in modules/custom/dynamic_menu and use this dynamic_menu.info.yml:

name: 'Dynamic menu'
type: module
description: 'Alters selected Drupal menu links using configuration and node data.'
package: 'Custom'
core_version_requirement: ^10 || ^11

Then add dynamic_menu.module with the hook. This example changes links to nodes of the case_file content type, prefixes the title and marks the link for styling:

<?php

/**
 * Implements hook_menu_link_alter().
 */
function dynamic_menu_menu_link_alter(
  array &$variables,
  string $router_path,
  array $original_map
): void {
  if ($router_path !== 'node/%node') {
    return;
  }

  $nid = $original_map['node'] ?? $original_map['nid'] ?? NULL;
  if (!is_numeric($nid)) {
    return;
  }

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $node = $node_storage->load((int) $nid);

  if (!$node) {
    return;
  }

  if (!$node->access('view')) {
    $variables['visible'] = FALSE;
    return;
  }

  if ($node->bundle() !== 'case_file') {
    return;
  }

  $configured_prefix = \Drupal::config('dynamic_menu.settings')
    ->get('case_file_prefix') ?: 'Case file';

  $status = $node->hasField('field_case_status')
    ? ($node->get('field_case_status')->value ?? NULL)
    : NULL;

  $prefix = $status === 'active'
    ? 'Active case file'
    : $configured_prefix;

  $variables['link']['title'] = t('@prefix: @title', [
    '@prefix' => $prefix,
    '@title' => $node->label(),
  ]);

  $variables['link']['attributes']['class'][] = 'menu-link--case-file';
}

The route map can expose the node identifier as either node or nid, depending on how the route was generated. Checking both avoids tying the hook to one menu item’s stored URI. The entity storage service loads the node, while access('view') prevents the title being changed for a user who cannot view it. Using t() with placeholders keeps the sentence translatable and sanitises dynamic values.

Put the prefix in config/install/dynamic_menu.settings.yml so it can be exported and deployed consistently:

case_file_prefix: 'Case file'

For a larger module, move entity and configuration work into a service with constructor injection. The hook should then remain a short adapter that calls that service. This improves dependency management and unit testing. Keep \Drupal:: calls in a prototype, but use services.yml for production code that other developers will maintain.

Load entities and customise labels

Loading an entity for every link can make a large menu slow. Filter by $router_path and content type before loading anything, as the example does, and use Drupal’s entity storage rather than a direct database query. The storage layer reuses entities loaded during the same request, but the hook should still avoid remote API calls and repeated field processing.

The title can combine several sources: an entity label, a workflow field, a configuration value and translated interface text. Use field names only after checking that the content type has them. If the destination also needs to change, assign a generated URL to $variables['link']['href']; $node->toUrl() is safer than constructing /node/ plus an ID because it respects route and alias processing.

Australian sites also need unambiguous dates. Store event times in the normal Drupal date field, format them with the site’s configured timezone, and use an unambiguous pattern such as j M Y for a menu label. Melbourne uses Australia/Melbourne, Sydney and Canberra use Australia/Sydney, and Brisbane uses Australia/Brisbane without daylight saving. Use Australian English such as “customise” and “organisation” in interface labels, and test long translated titles in the nav.

Apply access rules and visibility

A link title can expose as much information as its destination. Check entity access before using its label, and use the visible flag when an item should not be rendered for the current account. A short permission check can sit near the start of the hook:

if (
  $router_path === 'system.admin'
  && !\Drupal::currentUser()->hasPermission('access administration pages')
) {
  $variables['visible'] = FALSE;
}

Hiding a menu item is not authorisation. Drupal must still enforce the destination route’s access rules, and code should never reveal confidential data through a replacement title. A user who can guess a URL must receive the same 403 or login response regardless of what appears in the navigation.

Cache metadata must match the decision. Menu blocks normally vary with route access, but a label based on role or a custom permission can require user.roles or user.permissions as a cache context. Add the context to the menu render metadata rather than relying on a page-cache flush. For Australian councils, schools and community organisations, menu labels can also reveal client names or project codes; involve privacy owners when the Privacy Act 1988 or Spam Act 2003 may apply. Public-sector accessibility briefs commonly require WCAG 2.1 AA, so preserve meaningful link text and never use colour alone to convey a state.

Cache, deploy, and verify the change

Drupal caches menu trees, render arrays and sometimes complete pages, so a hook change may not appear immediately. Rebuild caches after enabling the module or changing configuration. Where a node field drives the label, confirm that editing the node invalidates the cached menu; add the node’s cache tag to the menu render metadata if the route does not already supply it. Test both anonymous and logged-in requests, because a shared cache entry can otherwise expose one account’s label to another.

Deploy the module and its configuration as reviewed code, enable it in the target environment, and clear caches in the normal release sequence. Useful Drupal 10 or 11 commands include drush pm:enable dynamic_menu, drush cr, and drush php:lint modules/custom/dynamic_menu/dynamic_menu.module. Check the actual HTML and keyboard path, not only the menu editor, because aliases, translated labels and access rules can change the final result.

Checks before deployment

Useful hook variations

The right approach depends on where the changing data lives and how much control the site needs.

Approach Best suited to Main advantage Main caution
hook_menu_link_alter() Small contextual changes to existing menu links Keeps normal menu editing and routing Must respect cache variation
hook_preprocess_menu() Wrapper, markup or tree-level presentation changes Works after links are assembled Less direct for entity-driven titles
Views or entity queries Automatically listing many entities Useful filters and relationships Requires query, display and cache tuning
Custom menu builder Bespoke navigation assembled from application data Maximum flexibility Highest development and maintenance cost

For most Drupal requirements, hook_menu_link_alter() offers the best balance: menu editors retain control of hierarchy, Drupal continues to own routing and access checks, and custom code remains limited to the values that genuinely need to change.