Magento 1.6 Menu Link Active State

Ahh Magento. So powerful but what a pain in the ass when you don’t work with it regularly.

So you’ve added custom menu items to your top.phtml

app/design/frontend/default/<strong>theme_name</strong>/template/navigation/top.phtml

It all works great but the .active class isn’t being applied to the menu item when you’re on said page.

For the home link

    <li class="home <?php echo (Mage::helper('core/url')->getCurrentUrl() === Mage::helper('core/url')->getHomeUrl()) ? "active" : ""; ?>"><a href="<?php echo $this->getUrl('')?>"><?php echo $this->__('Home') ?></a></li>

Note: What we’re doing here is we’re using built-in Magento methods and comparing the current url with the home url. If they’re the same, we append the active class to whatever other class we might have.

For any other link

    <li class="the-story <?php echo (strstr(Mage::helper('core/url')->getCurrentUrl(),"URL KEY HERE")) ? "active" : ""; ?>"><a href="<?php echo $this->getUrl('the-story')?>"><?php echo $this->__('The Story') ?></a></li>

Note: Similar to the home link code but this time we use the php function strstr() to see if the current page URL contains the URL key of the menu item page. If it does that mean we’re on that particular page so we append the .active class, same as above.

Hope this helps!

This entry was posted in Programming, Web. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted March 12, 2012 at 04:48 | Permalink

    Hi
    The above code does not work when caching is turned on. If you disable caching, it works fine.

    • Trev
      Posted March 12, 2012 at 10:49 | Permalink

      Thanks for the input. I’ll have a look into it. Do you have a solution yourself?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>