5

I want to add menu items to the Navigation menu dynamically, depending on certain states (example: user is logged in, etc). I assume I do this in theme_preprocess, but I can't seem to find the var to tweak.

Am I looking in the wrong place? Where is the best place to do this, and what is the best method?

  • I am having the same needs now. Did you figure out how this can be done? – Wei Ma Apr 23 '14 at 19:01
5

I'd suggest checking out hook_menu(). For example, the following implementation of hook_menu() placed in either a module or template.php should insert a menu item into the navigation menu for anonymous users. Take a look at the User module for some good examples of how to implement hook_menu() for different user roles.

function MODULE_menu() {
   $items = array();
   $items['the/menu/path'] = array(
   'access callback' => 'user_is_anonymous',  //or 'user_is_logged_in' to check if logged in
   'type' => MENU_NORMAL_ITEM,
   'menu_name' => 'navigation',
   'title' => t('Title of Menu Item'),
  );
  return $items;
}
  • If I understand correctly, that is how to create menus in the menu system. I'm wanting to refine a menu that is defined in the GUI, a built-in nav called Navigation. – Justin Nov 7 '11 at 0:12
  • The find the menu item and run the hook_menu_alter on it and add the access callback. – joedivic Nov 7 '11 at 2:11
  • 1
    Themes cannot implement hooks, except specific alter hooks in Drupal 7. – kiamlaluno Nov 7 '11 at 10:27
  • hook_menu_alter() only runs when the menu system is being rebuilt. I'm looking to refine the menu on the page load. – Justin Nov 8 '11 at 1:49
  • Golden oldie! The answer above would be fine. For non-code options, check out drupal.org/project/menu_item_visibility, drupal.org/project/menu_per_role, or drupal.org/project/custom_menu_perms. – Justin Aug 5 '14 at 13:37
5

I think you can create it by using menu_link_save().

$item = array(
  'link_path' => 'my_path',
  'link_title' => 'title',
  'menu_name' => 'header-top-menu', // Menu machine name, for example: main-menu
  'weight' => 0,
  'language' => $node->language,
  'plid' => 0, // Parent menu item, 0 if menu item is on top level
  'module' => 'menu',
);
menu_link_save($item);

You could use the code I am showing in a hook_update_N() implementation.

See also Drupal 7 Menu Link update through update.php.

  • FYI - you missed a end quote at the end of 'title – user1015214 Feb 16 '18 at 18:39

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.