Replacing Drupal 7 Menu Links With Images
I recently worked on a project where the main menu items were to be displayed as images. Of course, stylish menu items are usually displayed using text that's been styled with Cufón (or a similar solution) and using CSS sprites for the background. But in this case, there wasn't text.
Now, I could have worked on updating the Imagemenu module to work with Drupal 7, but there just wasn't enough time in the budget. So instead, I decided to use a hook in template.php to get the job done for me.
function yourtheme_menu_link__main_menu(array $variables) { $element = $variables['element']; $sub_menu = ''; $name = strtolower(strip_tags($element['#title'])); // Clean up the name if (strpos($name, ':')) { $name = substr($name, 0, strpos($name, ':')); } $pattern = '/[^a-z]+/'; $name = preg_replace($pattern, '', $name); // Add our classes $element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'] . ' ' . $name; // Ensure that our
tag WON'T be filtered $element['#localized_options']['html'] = TRUE; // And build our link, where image is located at yourtheme/images/menu/name.png $output = l('<img src="' . base_path() . drupal_get_path('theme', 'yourtheme') . '/images/menu/' . $name . '.png" alt="' . $element['#title'] . '" />', $element['#href'], $element['#localized_options']); return '<li>' . $output . "</li>\n"; }