Magento – How to add active state to CMS Page in Top Menu

magento-1.9navigationtopmenu

How to add active state to CMS Page in Top Menu?
I get active class if i'm on category page.
I'm add items to Top Navigation used categories rewrites urls in magento.

I need help.

Best Answer

Here is the proper way to add a cms page link to the main menu without using the event page_block_html_topmenu_gethtml_before.
This way you will be able to add an active state to it also.
So create an observer in one of your modules that can look like this:

public function addCmsPage($observer) 
{
    //your page identifier
    $cmsPageIdentifier = 'page_idendifier_here';
    //get the menu instance
    $menu = $observer->getMenu();
    //load the page
    $page = Mage::getModel('cms/page')->load($cmsPageIdentifier, $identifier);
    //if the page exists
    if ($page->getId()) {
        $active = false;
        // Get the full action name for the request.
        $fullActionName = Mage::app()->getFrontController()->getAction()->getFullActionName();
        //check if we are on the view page action for the required page
        if ($fullActionName == 'cms_page_view') {
             $pageId = Mage::app()->getRequest()->getParam('page_id', $this->getRequest()->getParam('id', false)); 
             if ($pageId == $page->getId()) {
                 $active = true;
             }
        }
        //build a new menu item node
        $data = array(
            'name' => $page->getTitle(),
            'id' => 'cms-'.$cmsPageIdentifier,
            'url' => Mage::getUrl('', array('_direct'=>$cmsPageIdentifier)),
            'is_active' => $active
        );
        $pageNode = new Varien_Data_Tree_Node($data, 'id', $tree, $menu);
        //attach the node to the menu
        $menu->addChild($pageNode);
    }
}