June 14, 2010

How to make categories and current page highlighting in PHP?

Question by Markus Ossi

I am trying to find some example code or best practices about making CMS-type categories with PHP.

This is a problem that has for sure been solved gazillion times but for some reason I am unable to find any example code using PHP about how to implement this.

As far as I can tell, there are two parts to the problem. The first one has to with the styling side of things:

  • outputting the link in the navigation so that the current page has a special style (class=”active”) and
  • to not print out the link for the current page.

The second part is handling categories, subcategories and the dynamic pages under the categories.

The second part seems pretty straightforward. I am thinking of making it so that the name of the category in the navigation is a link to categories.php?id=x and on this page I just print out the pages with that category id. Then, if the user klicks on a page he will be taken to pages.php?id=y.

However, I am not quite sure on how to make a navigation to check if we are now on the current page. Should I just use some case switch or what?

Any ideas or links to some good example code are much appreciated.

Answer by epalla

If you’re loading the page CMS-style presumably you’ve got some sort of page identifier that’s accessible within the code? A current_page_id or something like that? From there I usually just do this:

<ul id="menu"><?
foreach ($menu_items as $menu_item) {
    ?><li <?=($menu_item['page_id'] == $current_page_id) ? 'class="active"' : ''?>><a href="<?=$menu_item['link']?>"><?=$menu_item['title']?></a></li><?
}
?></ul>

Answer by Starx

no need for PHP, use CSS

a:active { color:#09f; }

UPDATE
use this little jquery code

$("*").find("a[href='"+window.location.href+"']").each(function(){
   $(this).addClass("current");
   $(this).attr('href',"#"); //nullifying the link
   //add your own logic here if needed
})

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!