Bulk generating menu hierarchies

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/';

 * 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);
Filed under:


That does look like a handy optional extra for devel_generate. Makes sense.

(I've use node_import with the menu/path support to quickly generate sitemaps/menus before now - not the same thing at all, but it gets a similar job done.)

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>, <java>, <php>. The supported tag styles are: <foo>, [foo].
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Ready for transformation?