Allow images in menu items in Drupal 7

Estimated reading time of this article: 2 minutes

Do you want to show images in menu items in Drupal 7? E.g. a Twitter logo beside some text?

You could (1) use the Menu Icons module or (2) add a simple theming function in your theme.

Add the following theming function to your template.php file in your theme:

<?php/** * Allows for images as menu items. * Just supply the an image path in the title. The image path will be replaced * with an img tag. The description is used as alt text and title. * Implements theme_menu_link().  * Reference: http://chrisshattuck.com/blog/how-use-images-menu-items-drupal-simple-preprocessing-function */function YOUR_THEME_menu_link($variables) {  $element = &$variables['element'];  $pattern = '/\S+\.(png|gif|jpg)\b/i';  if (preg_match($pattern, $element['#title'], $matches) > 0) {    $element['#title'] = preg_replace($pattern,       '<img alt = "' . $element['#localized_options']['attributes']['title'] . '" src = "' . url($matches[0]) . '" />',      $element['#title']);    $element['#localized_options']['html'] = TRUE;  }  return theme_menu_link($variables);}?>

An image path (recognized by the ending .png, .gif or .jpg) in the title of the menu item will be replaced with an image tag. E.g. "sites/default/files/images/twitter.png Follow" will show the Twitter image with the text Follow.