0

I just want to programmatically add some menu items to the main menu, but none of the answers I found worked. Some answers suggest using hook_menu(), others suggest using menu_link_save(). I followed what reported in Can I add a custom link to "Main Menu" via hook_menu? but it just doesn't work. There's no new item added, neither in the UI nor in the database.

function mymodule_menu() {
  $items['my/path'] = array(
    'title' => 'Title',
    'page callback' => 'page_creator_function',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

Also I found How and where do I programmatically add a menu to the Navigation menu?. Answer #2 says that using menu_link_save() is the way to go, but I could not get it to work. Do I have to place the code in a certain location or a special hook?

$item = array(
  'link_path' => 'my_path',
  'link_title' => 'Title',
  'menu_name' => 'main-menu', 
  'weight' => 0,
  'language' => 'en',
  'plid' => 0,
  'module' => 'menu',
);
menu_link_save($item);

Since both answers didn't work out, it seems that I am missing a crucial point. Could anyone say what's going on here?

  • your first hook should work, so if the menu item doesn't show, try to clear all caches and if no joy, try to debug and see where the error might lie... for example add a dpm inside your hook to see if it's even being called. – longboardnode Feb 12 '18 at 18:52
  • As side note, in the second snippet you show there is a missing string delimiter, in the third line. – kiamlaluno Feb 17 '18 at 15:23
0

After a hard time I figured out what hampered the execution of the above code: clearing caches isn't enough to see the results. I had to use devels menu reset (/devel/menu/reset). Using drush's drush eval 'menu_rebuild();' as mentioned at How do I call the menu_rebuild function in Drupal 7? somehow does not work. I do not know why.

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.