[Drupal] How to give images for menu items

| | 1 min read

In Drupal, while adding a menu item, we can give it a title, description, path and such details. It is not possible to give images for these menu items at the time of creation, by default. If you are looking for a solution, then read on.

This particular task can be achieved by overriding the theme function theme_menu_item_link() in our theme's template.php

Use the below function in your template.php :


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);
} 

Make sure that you change YOUR_THEME in the function to the name of your theme.

So while adding a menu item, give the path of the image in the field 'Menu link title' and fill the rest fields as usual. You could see the result after saving the menu. Good Luck.