blog-banner

Drupal : Add An Icon To The Menu Links

  • Drupal
  • Drupal Menu
  • Drupal Planet

Drupal 8 - Change Icon Menu Link Programmatically

 

We all like decorated items more than normal ones. Everyone likes to add icon/image to their site's menu links but we need some tricks to add that to our Drupal site's menu link. I am going to show you various methods to add an icon/image to the drupal menu links.

1. theme_menu_link() : 

 

It would return Html elements for the menu and it's a submenu. We can change the menu HTML elements using this function and this function must be written in our theme's template.php file. In this example, I am going to add icons to the main menu.

/**
 * Implementation of theme_menu_link__MENU_NAME().
 */
function THEME_NAME_menu_link__main_menu(array $variables) {
  $element = $variables ['element'];
  $sub_menu = '';

  if ($element ['#below']) {
    $sub_menu = drupal_render($element ['#below']);
  }
  $icon = 'icon-' . $element['#title'];
  $output = l($icon . $element ['#title'], $element ['#href'], $element ['#localized_options']);
  return '<li' . drupal_attributes($element ['#attributes']) . '>' . $output . $sub_menu . "\n";
}

This will add our new unique class to all main menu links, we could simply add the icons with the class using CSS style.

2. Menu Icons :

 

The menu icons are a drupal contributed module. It is one of the simplest solutions to add icons/images through UI. This module allows you to upload an image in the menu-item configuration form.

3. Menu Html :

 

The menu HTML is also a Drupal-contributed module. It allows you to add HTML elements in the menu link title field, so we could simply add the icon's HTML element in the title field, and then we could style them using CSS.

If you are using Glyphicons on your site, then that can be done with the following steps:

  1. Go to the menu item configuration page.
  2. Add the menu link title like this Menu title
  3. Enable Menu HTML options.
  4. Save the menu links.

Note * :

Get awesome tech content in your inbox