I seem to run into this problem frequently and can never find a solution. I have a Wordpress site with a top navigation. Since this is in my header.php, and used on all pages, I cannot hardcode my active menu state for each page.
How can I dynamically set the activate state to work for each page?
Here is my current nav code:
<nav id="main-menu" class="padbot">
<ul id="ce">
<li class="cemenu"><a href="<?php echo $base_url;?>/about">About</a></li>
<li class="cemenu"><a href="<?php echo $base_url;?>/consulting">Consulting</a></li>
<li class="cemenu"><a href="<?php echo $base_url;?>/intelligence">Intelligence</a></li>
<li class="cemenu"><a href="<?php echo $base_url;?>/academy">Academy</a></li>
<li class="cemenu"><a href="<?php echo $base_url;?>/blog">Blog</a></li>
<li class="cemenu"><a href="<?php echo $base_url;?>/contact">Contact</a></li>
</ul>
I've already setup a CSS class called "active" that has my active state properties. Ideally, what I'm looking for is when your on the "About" page (or any of the other pages), the class I created for the active state will be appended to the current li classes's.
Example:
<li class="cemenu active"><a href="<?php echo $base_url;?>/about">About</a></li>
Thanks!
First, there is a css pseudo class prepared for styling 'active' links :
For your situation, you would have to add this class to your styling :
But your needs seems more on the PHP side than the CSS, perhaps someone else will help you with that part. There would be a javascript solution with jQuery, finding the actual location then inject a css selector to the proper element.
Check this article and this other one about wordpress. It will help you.
Stack Overflow references :
You can do this way:
This will add the
active
class to the<a>
which contains thepage
from the url.and if you want to add class to its parent li the replace the last line to this and css class should be like this:
or
just tryout the fiddle here
You could use preg_replace() to add
class="active"
like this:try something like this:
It may be worth looking into using wordpres functions such as get_page_link which would be nicer than using the Server super global as that's not nice. This would also fail if you have wordpress in a folder and not the document root, it's just a simple example to get you started :)
You can try like this
And then in your home page
And in your contact page
you could try something along the lines of