How to create menu and menu items programmatically in Drupal

How to create menu items programmatically in Drupal 7

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.

We use this approach to development quite often when, as part of our Drupal support services, we prepare a large batch of changes to be deployed all at ones. It also comes handy when you are building a corporate website on Drupal in a CI setup and want to fill it in with dummy data generated from code.

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 /devel/php before you run hook_update_N.

3. Best practices for software development teams