Drupal

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.


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);
    }
  }
}

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.