How to create menu and menu items programmatically in Drupal

How to create menu items programmatically in Drupal


When you use code driven development on websites based on Drupal sometimes you have to create a menu or a menu item programmatically in hook_update_N.

The below code snippets show you how to do that in Drupal 7.

How to create a menu programmatically:

$menu = array( 'menu_name' => 'header-top-menu', // Drupal menu machine name 'title' => 'Header top menu', // Drupal menu display name 'description' => 'Header top menu', // Optional menu description ); menu_save($menu);

How to create a menu link programmatically:

$node = node_load(123); // Load some node from database and use them for new menu link. $item = array( 'link_path' => 'node/' . $node->nid, 'link_title' => $node->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);

Remember that you can test this code using Devel module on page /deve/php before you run hook_update_N.

Need a team of Drupal and PHP web development experts?

Contact us now!