Home    Articles


How to add links in the top menu of magento | Code Download Available


The proper way to add custom links into magento’s menu is to create an observer that will do it automaticly for you.

The code can be downloaded from here: Download but we recomend you to read the code to understand it.



I know that is more work involved but this is a great solution to add links into the menu and can be easily modified in future.
First of all we need to set up the observer with a hook on creating the menu.

This is the config that will make the hooks and needs to be added into the module, our code is a module without any interface.

1) The config file:

<?xml version="1.0" encoding="UTF-8"?>

Now we need to create the method that will create our menu. This method will be called when the hook “page_block_html_topmenu_gethtml_before” will be fired.

By modifing the method, you can create custom things.

2) The code:

class W3bdeveloper_ChangeMenu_Model_Observer
     * Exports an order after it is placed
     * @param Varien_Event_Observer $observer observer object 
     * @return boolean
    public function addToMenu(Varien_Event_Observer $observer)
        $menu = $observer->getMenu();
	    $tree = $menu->getTree();
	    $node = new Varien_Data_Tree_Node(array(
	            'name'   => 'Categories',
	            'id'     => 'categories',
	            'url'    => Mage::getUrl(), // point somewhere
	    ), 'id', $tree, $menu);
	    // Children menu items
	    $collection = Mage::getResourceModel('catalog/category_collection')
	    foreach ($collection as $category) 
	        $tree = $node->getTree();
	        $data = array(
	            'name'   => $category->getName(),
	            'id'     => 'category-node-'.$category->getId(),
	            'url'    => $category->getUrl(),
	        $subNode = new Varien_Data_Tree_Node($data, 'id', $tree, $node);

3)The Conclusion

This method of adding link to the menu is nicer than modifing the template file, it is more elegant.