I am trying to add a menu item to a custom menu programmatically in Drupal 6 and have almost gotten it but ran into a weird problem. I can add the item to the menu using the code: drupal_execute('menu_edit_item', $item_array, 'add', NULL, array('menu_name' => $menu_name)); drupal_flush_all_caches(); This somewhat works, but for the link to actually show up in the menu I have to either save the page twice, or save the page and clear the cache from Admin > Performance. Does anyone know why I need to flush the caches twice, or is there a better way to do this? Let me know if you need any more information, I included what I thought was relevant but I may have left something out.
3 Answers
To add menu items use hook_menu():
This hook enables modules to register paths in order to define how URL requests are handled. Paths may be registered for URL handling only, or they can register a link to be placed in a menu (usually the Navigation menu).
example:
function YOUR_MODULE_NAME_menu() { $items['a/b/c'] = array( 'title' => 'Example menu', 'page callback' => 'example_callback', 'access arguments' => array('access content'), 'type' => MENU_NORMAL_ITEM, 'menu_name' => 'your-custom-menu-name', ); return $items; }
To learn more about hooks see here
- 1Thanks, but this doesn't work for a custom menu. I understand how hook_menu works. I need to add a link to a custom menu I created programmatically.Kyle Piontek– Kyle Piontek2012-07-24 11:38:45 +00:00Commented Jul 24, 2012 at 11:38
- OK. see the edited post(menu_name).Hamid Nikmehr– Hamid Nikmehr2012-07-24 11:49:29 +00:00Commented Jul 24, 2012 at 11:49
- hook_menu is definitely not for adding links to menus.Adam Balsam– Adam Balsam2014-04-23 17:20:28 +00:00Commented Apr 23, 2014 at 17:20
The API you are looking for is menu_link_save. And, as documented use menu_cache_clear_all after.
Try menu_rebuild() instead of flushing caches.
(Re)populate the database tables used by various menu functions.
This function will clear and populate the {menu_router} table, add entries to {menu_links} for new router items, then remove stale items from {menu_links}. If called from update.php or install.php, it will also schedule a call to itself on the first real page load from menu_execute_active_handler(), because the maintenance page environment is different and leaves stale data in the menu tables.