Create a menu item programmatically

Public

Here is a toolkit function to create one menu item. Creation is saved in the watchdog and this function cares about i18n.

</> CopyGet raw version
php
  1. /**
  2.  * Helper function to create a menu item and notify it in the Watchdog
  3.  * @param array $item_infos Informations of the menu item as passed to
  4.  * menu_link_save()
  5.  * @return int $mlid ID (mlid) of the new menu item
  6.  */
  7. function _my_module_create_menu_item($item_infos) {
  8. //We provide fallback values for all mandatory menu item informations:
  9. // "new link" as title, <front> as the path, and main-menu as the target menu.
  10. $item_infos += array(
  11. 'link_title' => 'new link',
  12. 'link_path' => '<front>',
  13. 'menu_name' => 'main-menu',
  14. 'plid' => 0,
  15. );
  16. $plid = $item_infos['plid'];
  17.  
  18. $itemExists = db_query(
  19. "SELECT mlid from {menu_links}
  20. WHERE link_title=:link_title
  21. AND link_path=:link_path
  22. AND plid=:link_plid
  23. AND menu_name=:menu_name",
  24. array(
  25. ':link_title' => $item_infos['link_title'],
  26. ':link_path' => $item_infos['link_path'],
  27. ':link_plid' => $item_infos['plid'],
  28. ':menu_name' => $item_infos['menu_name'],
  29. ))->fetchField();
  30.  
  31. if (!$itemExists) {
  32. // manage multi-lingual menus using i18n
  33. if (module_exists('i18n_menu')) {
  34. if (i18n_menu_mode($item_infos['menu_name'], I18N_MODE_LOCALIZE)) {
  35. $item_infos['customized'] = 1;
  36. }
  37. }
  38.  
  39. $mlid = menu_link_save($item_infos);
  40. }
  41.  
  42. if (!empty($mlid)) {
  43. $wd_sentence = '@linktitle menu link has been created (mlid: @mlid)';
  44. if (!empty($item_infos['plid'])) $wd_sentence .= ' under item @plid';
  45. $wd_sentence .= ' in the @menuname menu';
  46.  
  47. watchdog('my_module', $wd_sentence, array(
  48. '@linktitle' => $item_infos['link_title'],
  49. '@mlid' => $mlid,
  50. '@plid' => $item_infos['plid'],
  51. '@menuname' => $item_infos['menu_name'])
  52. );
  53. }
  54. else {
  55. watchdog('my_module', 'An error occured on creating @linktitle menu item in the menu @menuname', array(
  56. '@linktitle' => $item_infos['link_title'],
  57. '@mlid' => $mlid,
  58. '@plid' => $item_infos['plid'],
  59. '@menuname' => $item_infos['menu_name'])
  60. );
  61. }
  62. return $mlid;
  63. }