How to Programmatically Modify Menu Links in Drupal 11
Yogesh Kushwaha, in a tutorial published on his blog, explains how to programmatically change menu links in Drupal 11 to support dynamic navigation. The guide begins with an overview of Drupal’s menu system, highlighting that menus are now entities in the core, making them fieldable and more flexible. A menu link pointing to /user/2
is created via the UI as an example. The goal is to change this link programmatically to point to a different user ID, such as /user/4
, based on context.
The solution involves creating a custom module named broute
and using the hook_link_alter
hook, implemented in an object-oriented way. The code identifies the targeted menu link by its label and updates its route parameters. This allows developers to tailor menu behaviour for different user roles or conditions. The tutorial provides clear steps and code snippets for implementing this in Drupal 11.