I’m trying get the code below to always highlight the current page of a theme that I’m working on but it does nothing. The HTML part is as shown below the script. Any suggestions or solution for the fix.
<script type="text/javascript">
var url = window.location.href;
url = url.substr(url.lastIndexOf("/") + 1);
$("#navbar").find("a[href='" + url + "']").addClass("current");
</script>
<div id="navbar">
<ul>
<li><a href="index.php">home</a></li>
<li><a href="services/">services</a></li>
<li><a href="procedure/">procedure</a></li>
<li><a href="about-us/">about</a></li>
<li><a href="contact-us/">contact</a></li>
</ul>
</div>
You need to look into WP Nav Menu.
I’m guessing this is a theme you’re developing? If so, Register a Nav Menu in your functions.php file. What this will do is allow you to define your menu in the WordPress dashboard (Appearance->Menus), and customize it however you like.
The reason why I’m suggesting this is that not only will it allow you to have total control over your Menu in a very intuitive way, but it also defines all the classes you could possibly need for your stylesheet automatically (including current items, and ancestry).
That is the cleanest option you have at your disposal. You can also look into WP List Pages for a similar (albeit, more limited) solution.
Otherwise, you’ll have to do something dirty like this:
Replace $services_ID, $procedure_ID, etc. with their respective Page IDs, and if the current ID matches any one of them, that item will have a class of “current” applied to it, which you can then target in your stylesheet.
The main reason why I suggest a server-side solution over using any kind of jQuery is that this is not a task that is suited specifically for jQuery itself.
While the jQuery library is a powerful tool, WordPress has all of the built-in functionality you need to detect everything you want to detect in this instance. Let the server do as much work as possible before letting the client’s browser take over. Otherwise, you’ll be looking at some serious load times.
UPDATE:
Based on your last comment, if you’re going to go with the messy way and you don’t want to be bothered with finding IDs of your pages, you can also do this:
UPDATE BASED ON LAST COMMENT:
Now that you’re using wp_nav_menu, you can target the current menu item with CSS. Here’s an example that will turn the background of the current item to red:
Apply these rules either in your header, or preferably in your main style.css file. Good luck!