Creating a dynamic menu link in Drupal

Sometimes you'll need to create a menu link that is different for each user that views it. The simplest way to do this is to create a small custom module that will add the menu link and generate a dynamic URL.

In my case, I wanted a link title 'My Company' that would redirect the user to their own Organic Group.

What to do

  • Create a menu entry ``` 'My Company', 'description' => 'View your company\'s page', 'page callback' => 'grasmash_my_company_link', 'access callback' => 'grasmash_user_has_company', 'expanded' => TRUE, 'weight' => -100, 'menu_name' => 'primary-links', ); return $items; } ?> ``` The page and access callbacks are functions that I'm about to create. For more information about the hook_menu function, checkout the hook_menu() entry in Drupal's API. I'd also recommend downloading the Examples for Developers module to get a good sense of how Drupal's basic functions work.
  • Next, create a function that will actually determine the user's company (OG) ``` uid)); return $nid; } ?> ```
  • Let's also create function for the access callback. This will determine whether the user should be able to see the link. ``` ```
  • Lastly, let's redirect the user to the correct node after they click on the link: ``` ```

And there you have it. Feel free to customize the MySQL query to change which node the user will be redirected to.

A quick note on what we didn't do

We didn't add code that would dynamically change the $items['my-company'] URL. Why? because Drupal only checks on that URL when the menu system needs to be rebuilt. Instead, you need to choose a static URL and write a function that will dynamically load content or redirect the user when that URL is visited.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.