Ordering Off the Menu: Custom Highlighting in Drupal 6


Drupal's menu system is highly robust and really customizable through the GUI. One common complaint is that it doesn't highlight parent menu items when one of their children is selected, but this can be solved using Chapter Three's Menutrails module.

However, what if you want more custom control over your menu highlighting? One customer of mine wanted menus on some pages highlighted depending on the path. Good gravy, how do we do that? Here's one way.

The Code

This code is taken from the Drupal 6 API documentation for the theme_links() function. In order to override the theme_links function, you'll want to open your theme's template.php file and create a new function called:

function yourthemename_links($links, $attributes = array('class' => 'links')) {

Go ahead and copy/paste the body of the function straight from the documentation.

We're going to focus on these lines:

if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '' && drupal_is_front_page()))
&& (empty($link['language']) || $link['language']->language == $language->language)) {

For my application, I'm going to parse the current path and highlight the menu item that matches the first part of the path, before the first slash. So for example, I want to highlight the menu item "Blog" with the url /blog even if the user is at /blog/entry_name. Here's the code I ended up with:

$alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
$path_parts = explode('/', $alias);
if(!isset($path_parts[0])) $path_parts[0] = FALSE;
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '' && drupal_is_front_page()) || ($path_parts[0] === drupal_get_path_alias($link['href'])))
&& (empty($link['language']) || $link['language']->language == $language->language)) {

Happy themeing!

1 Comment

Did you enjoy this post? Please spread the word.