I’m trying to add a class to all the links of the various menus on the page, in order to activate the active state when the relative page is loaded.
HTML
<div id = "content">
...
<div class = "menu-item">
<a href="/page1/" class="menu-link"> Page1 </a>
</div>
...
</div>
JS
<script>
jQuery (function ($) {
var pgurl = window.location.href.substr (window.location.href.lastIndexOf ("/") + 1);
$ (". menu-item> a"). each (function () {
if ($ (this) .attr ("href") == pgurl || $ (this) .attr ("href") == '')
$ (this) .addClass ("active");
// $ (this) .parent ("li"). addClass ("active");
})
});
</script>
I’ve tried other scripts too but they don’t work.
I believe the problem is related to the HREF URL.
In HTML, I pass a value like / page1 / but in WordPress, the correct permalink is / parent / page1 /.
How can I fix and improve the script?
3
Answers
Please try:
You can test this code with your real urls.
Retrieving the last valid "word" (in
abcpage1
ispage1
or inxyzpage1
ispage1
) for both url, page and menu item url. Finally I make the comparison between the two.One more thing that would be done, remove any hashes (
urlpage#abc
) and parameters (urlpage?Param=value
)EDIT
To be more clear, the real end code will be this:
According to WordPress Code reference page: wp_nav_menu()#menu-item-css-classes, the class below is added to menu items that correspond to the currently rendered page.
.current-menu-item
So, basically what you can do is to just add the corresponding css for the class names which are automatically generated by wordpress:
You don’t need to use jQuery.