30th April 2010

Dynamically setting the active menu trail without menu items

Alli Price
Developer

When building a Drupal site with a multi-layer navigation system maintaining active trail is very important. This is something we encountered when developing the new International Policy Network website, where the site is split into seven top level sections with common subsections under each such as "News" for example. The news section would list news nodes categorised by the top level.

Making use of menu items per node isn’t feasible, so we made use of menu_set_item.

The reason why we need to do this is because we need the secondary links menu to output our subsection links entirely without a menu item for the node.

What the below code will achieve is, when viewing a full news node, active menu item will be set to ‘subsection/news’ - which is the url of our news node listing.

/** * Implements hook_nodeapi(). */ function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) { if ($op == 'view' && $node->type == 'news' && !$a3 && arg(0) == 'node') { $item = menu_get_item(); $item['href'] = 'subsection/news'; menu_set_item(NULL, $item); } }

That's it!