Monday, January 7, 2013

Adding Menu Icons in Superfish Module for Drupal 7

I had a project dropped on my lap a few weeks ago. Obviously, It was already behind schedule. One of the features was to implement a dropdown menu with a home icon for the home link. Unfortunately, I found out that the superfish module bypasses the drupal methods for the menus. So, this is how I managed to get it modified. Please note that this is not upgrade friendly. You will have implement this solution again if you upgrade the superfish module. I performed the quick and dirty solution since I was already behind schedule. The better approach would be to override methods in your theme template file.

1) Open superfish.module file.

2) Scroll down to theme_superfish_build method.

3) Add your new logic to the last section of the method where there is concatenation of the output html.

My logic was this:

$pattern = '/\S+\.(png|gif|jpg)\b/i';

        if(preg_match($pattern, $menu_item['link']['title'], $matches) > 0)
        {
            $output['content'] .= '<a href="'.url($menu_item['link']['link_path']).'">'.preg_replace($pattern,'<img alt = "' . $menu_item['link']['title'] . '" src = "' . url($matches[0]) . '" />',
                $menu_item['link']['title']).'</a>';
        }
        else
        {
            $output['content'] .= l($menu_item['link']['title'], $menu_item['link']['link_path'], $link_options);
        }

This logic transforms a url path in the title that contains an image file extension into an image tag. This worked good for my solution, but would not have worked well if all my menu items needed an image. That is because the title would be displayed in other modules such as menu block. I would have needed a much more complicated snippet to handle an entire menu.

No comments:

Post a Comment