WP Dynamic Highlight Menu
OK, so I have a major problem with brainstorming and researching a certain item, function, procedure, trick, hack etc for the current project I’m working on, never writing it down, and having to re-learn it all over again the next time I need to use the same thing. Since I’ve been trying to keep content churning out on this site, I figured I could start posting stuff here to at least serve as a repository for all the stuff I will never remember off the top of my head [since no one really reads the site anyways]. Anywho, I found myself working on a WordPress project recently that had the simple need of a dynamic menu that highlighted the current page. Most people choose to go the easy route and use code similar to this:
<ul id="nav">
<li<?php if ( is_home() ) { echo 'class="current"'; } ?>><a href="#">Gallery</a></li>
<li<?php if ( is_page('about') ) { echo 'class="current"'; } ?>><a href="#">About</a></li>
<li<?php if ( is_page('submit') ) { echo 'class="current"'; } ?>><a href="#">Submit</a></li>
</ul>
<li<?php if ( is_home() ) { echo 'class="current"'; } ?>><a href="#">Gallery</a></li>
<li<?php if ( is_page('about') ) { echo 'class="current"'; } ?>><a href="#">About</a></li>
<li<?php if ( is_page('submit') ) { echo 'class="current"'; } ?>><a href="#">Submit</a></li>
</ul>
Whereas this will do the trick for a finite menu where the names will never change, it’s not what I wanted for my client. With a little research in to some of the changes in the past couple versions of WP, I was able to get the desired results with a few lines of code:
<div id=”menu”>
<!–Main navigation menu–>
<ul>
<?php wp_page_menu(’show_home=1′); ?>
</ul>
</div><!– menu –>
You might ask “How does it know what the current page is?” I say…..”WordPress is awesome and takes care of it for you these days! When using the wp_page_menu() function, the “current_page_item” class is automatically added to the current selected page. The end result will be this:
<li class="current_page_item">
Rather than:
<li class="page_item page-item-2">
So the accompanying CSS would just apply the “current” styling to the “current_page_item” class, and you’re done!!!
The way I chose to do it makes for less code on the developer’s side, and also allows menu items to be updated dynamically when a user adds a new page, deletes and old one, updates a pages name, or changes the order. While I appreciate WP’s addition of the wp_page_menu() function, I wish they would add the options to specify what item the class is attached to (list item or link), as well as the option to specify your own class name in place of “current_page_item.” I hope someone else finds this to be useful. As always I encourage comments and discussion!
-Phenix
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.




Comments
// Begin Comments & Trackbacks ?>No comments yet.
Leave a comment