The Web Tech Blog
Subscribe to this blog
Aug
2007
Dynamic Wordpress Nav Menus: Explained
Achieving active states on specific pages and categories has never been easier!
I have come across many developers online who have simply given up too easily when it comes to automating their Wordpress installations. I can’t blame most of them though…there really isn’t a whole lot of concrete documentation on this subject. Not for novices/beginners, anyway.
The following is the method I used personally to build this site’s nav menu:
(place this code in between your head tags and edit as you see fit)
<?php
if ( is_home()) { $active = 'one'; }
elseif ( is_page('14') ) { $active = 'two'; }
elseif ( is_page('15') ) { $active = 'three'; }
elseif ( is_page('16') ) { $active = 'four'; }
elseif ( is_page('17') ) { $active = 'five‘; }
elseif ( in_category(4) ) { $active = ‘five‘; }
elseif ( is_page(’18′) ) { $active = ’six’; }
elseif ( is_page(’19′) ) { $active = ’seven’; }
elseif ( is_page(’20′) ) { $active = ‘eight’; }
elseif ( is_page(’39′) ) { $active = ‘eight’; }
?>
As you can see, css id “five” is assigned to both Page17 (Blog) and Category4 (Blog Category). Makes sense now, huh? You can add to this list or subtract from it in order to work with your blog structure.
Now that you’ve assigned each page/category an “ID”, let’s write out some CSS that will go right underneath the above code in your header template:
#<?php echo $active; ?> a:link {
background-color: #333333;
}
#<?php echo $active; ?> a:visited {
background-color: #333333;
}
This appends a “#” to the css ID of the current page.
Your nav list should look something like this:
<li id="one"><a href="http://www.domain.com/">Home</a></li>
<li id="two"><a href="http://www.domain.com/products">Products</a></li>
And so on...
Hope this helps! If you need more help, feel free to leave a comment and I’ll try and help you out.









