Dynamically Assign a CSS Class to the Current Page

Have you ever wondered how to assign a CSS class to the hyperlink of the currently active/open page so that you can make it clear to visitors the page they’re on by looking at the links? This functionality usually comes built-in to menus in most themes (especially WordPress), but what if you want to manually add links to a page and have those custom-made hyperlinks do something when their specific page is open? Simple – just add some PHP code! 

In my case, I had manually added a few links in my theme’s footer (footer.php) for the About page, the Contact page, etc., and I wanted to be able to use CSS to bring attention to the relevant hyperlink when on that page. Here’s how I did it:

 <ul class="footermenu">
    <li><a class="listitem<?php if (is_page('about')) echo ' active'; ?>" href="/about">About</a></li>
    <li><a class="listitem<?php if (is_page('contact')) echo ' active'; ?>" href="/contact">Contact</a></li>
    <li><a class="listitem<?php if (is_page('legal')) echo ' active'; ?>" href="/legal">Legal Stuff</a></li>
 </ul>

…etc. As you can see, I started with a standard href tag that already defined each list item as being in a “listitem” class, but then I inserted PHP code that also gives the current page the “active” class as well. So now when you visit the “About” page at this site, the HTML output will show class=”listitem active” and then will revert to simply class=”listitem” when you open a different page that still shows that “About” link in the footer. Easy!

Just be careful not to confuse the “.active” class with the default/built-in “:active” link state! (i.e., it allows you to tell CSS what to do to the link as it’s being clicked on.) If this is a potential minefield of confusion for you, just change the above code from ‘ active’ to ‘ current’ or whatever makes sense to you.

Happy coding,

Steve