Thursday, April 19, 2012

Drupal add background images to primary links


Drupal is the most powerful free CMS I have ever seen. Today's tip is about making image menu, or a menu with text and background images inside drupal.

To make this follow the steps below :

1- Open your template.php file ( found inside your theme folder ), find the line :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

and add the following code just before it :
<?php
function primary_links_icons_bg() {
  $links = menu_primary_links();
  $level_tmp = explode('-', key($links));
  $level = $level_tmp[0];
  $output = "<ul class=\"primary-links-$level\">\n";    
  if ($links) {
    foreach ($links as $link) {
       $link = l($link['title'], $link['href'], $link['attributes'], $link['query'], $link['fragment']);
       $cssid = str_replace(' ', '_', strip_tags($link));
       $output .= '<li id="'.$cssid.'">' . $link . '</li>'; 
    }; 
    $output .= '</ul>';
  }
  return $output;
}
?>

2- Open your page.tpl.php ( found in your theme's folder ) and search for navigation code, in most themes it is called ( $primary_links ), search for it, it will look like :

<?php
if ($primary_links): ?>

SOME CODE [replace this code]

<?php endif; ?>

Replace the SOME CODE with the following code :

<div id="navigation">
     <?php print primary_links_icons_bg(); // function name must be the same as created in template  ?>
</div>

3- Now if you check you navigation links, you will find that every menu item has its own id, you can put background image in the css file for each item.

and that's it. now you can make a very neat and attractive menus using drupal.

No comments:

Post a Comment