Magento add / delete / edit top menu entries

Yesterday I discovered two really nice and new Magento events – page_block_html_topmenu_gethtml_before and page_block_html_topmenu_gethtml_after. These are great entry points in order to add, delete or edit top menu entries. Unfortunately, they are only available in Magento > 1.7.

In my case, I wanted to add a new „More“ category in which all categories that do not fit into the top menu bar are shown. Hence, I registered for the page_block_html_topmenu_gethtml_before event and implemented the logic in order to edit the menu entries:

/**
* Shows only six categories and wraps the other ones in a new "More" submenu.
*
* @param Varien_Event_Observer $observer Observer
* @event page_block_html_topmenu_gethtml_before
* @return void
*/
public function pageBlockHtmlTopmenuGethtmlBefore(Varien_Event_Observer $observer)
{
    /** @var $menu Varien_Data_Tree_Node */
    $menu = $observer->getEvent()->getMenu();
    /** @var $menuCollection Varien_Data_Tree_Node_Collection */
    $menuCollection = $menu->getChildren();

    $i = 0;
    $active = false;
    $data = array(
        'name' => Mage::helper('core')->__('More'),
        'id' => 'category-node-more'
    );
    $tree = new Varien_Data_Tree();
    $node = new Varien_Data_Tree_Node($data, 'id', $tree, $menu);
    /** @var $menuItem Varien_Data_Tree_Node */
    foreach ($menuCollection as $menuItem) {
        // show only six categories and a "More" submenu
        if ($i > 5) {
            // if one of the submenu items is active, the "More" submenu should be active
            if ($menuItem->getIsActive()) {
                $active = true;
            }
            // delete the item from the old menu and add it to the new submenu
            $menuCollection->delete($menuItem);
            $node->addChild($menuItem);
        }
        $i++;
    }
    $node->setData('is_active', $active);
    $menuCollection->add($node);
}

And that’s it. Isn’t it a really nice, clean and simple method to alter the top menu? Another common use case is to add a „Home“ link at the beginning of the top menu – should be no problem with the code snippet above, right? 😉 What did you do with the new events? How did you edited the top menu? Let me know in the comments!

If you want to read more about the new possiblities, have a look at Carmen Wingenbach’s german blog post „Magento: Neu in Version 1.7: das Top Menü„.

Ein Gedanke zu „Magento add / delete / edit top menu entries“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert