Blog

Bulk generating menu hierarchies

Written by Metal Toad Staff | Oct 7, 2009 12:00:00 AM
Filed under:

If you have ever needed to bulk generate menu items in Drupal (I used this for theming some drop-downs), here is a snippet to accomplish it. The third parameter is for recursively creating a hierarchy, so be careful with it – you can blow up the menu admin page in a hurry!

This code requires the devel module; the ambitious reader might consider adapting this to patch devel itself.

When you're finished, the generated items can be cleared quickly with DELETE FROM {menu_links} WHERE link_path = 'http://example.com/';

<?php
/**
 * Bulk generate menu links.
 * @param $count Number of links to generate.
 * @param $plid  Menu id  of the parent item.
 * @param $depth Recursion depth; 0 for a single set of menu items.
 */
function menugen($count, $plid = NULL, $depth = 0) {
  require_once(drupal_get_path('module', 'devel_generate') . '/devel_generate.inc');
  foreach (range(1,$count) as $x) {
    $item = array(
      'menu_name' => 'primary-links',
      'link_path' => 'http://example.com/',
      'link_title' => devel_create_greeking(2, TRUE),
    );
    if (! empty($plid)) {
      $item['plid'] = $plid;
    }
    $mlid = menu_link_save($item);
 
    if($depth != 0) {
      menugen($count, $mlid, $depth - 1);
    }
  }
}