Drupal: Create Placeholder and Separator Menu Items via Your Theme

by Chadwick Wood
October 19th, 2010

Sometimes you just want to break up your Drupal menus into sub-menus, but with headers that aren't links themselves. For example, say you want a menu like the one pictured here, and you'd like to implement it as one menu tree within Drupal. "Looking & Telling" and "Making" need to be menu items, but they aren't actually links to pages; they're just there to group menu items in a nice way. There is the Special Menu Items module to do it, but it does currently have some bugs, and there is actually a simple, theme-based way to achieve the same thing. Here's how.

Basic Idea

The basic idea behind this technique is to look for any menu item that links to a specific (nonsense) URL, and render it as text instead of a link. In this example, any menu item that you want rendered just as text will have "http://nolink" as the Path value for that menu item. Your theme will look at every menu item it is rendering, and check for the special URL. If it's found, the menu item will be rendered as text and not a link. Here's a screenshot of what the "Looking & Telling" menu item has:

Override theme_menu_item_link

So, you have to override theme_menu_item_link() in template.php for your theme. As with any theme function override, I always start with the source of the original function from the Drupal API, then modify it as needed. Here is the modified code:

function mytheme_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }

  // if the "href" value of this link is our special URL,
  // render as a span instead of a link
  if ($link['href'] == 'http://nolink') {
    return ''.check_plain($link['title']).'';
  }
  else {
    return l($link['title'], $link['href'], $link['localized_options']);
  }
}

Put that code in your template.php file, then clear your theme registry, and you should be ready to go. My function wraps the placeholder items in a span with a class, so that I can style the placeholders how I want in CSS.

The Menu Structure

Here is a picture of the structure of the menu in this example:

Important to note is that the placeholder menu items we create are parents of sub-items in the menu tree. Since the placeholders aren't pages that can be visited, we need to make sure the "Expanded" checkbox is checked for those placeholder items, so that the sub-items are shown.

Leave your questions in the comments!