'Add active class to link with current page

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?



Solution 1:[1]

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:

.current-menu-item {
    color: red; // change the color of the current active page to #red;
}
.current-menu-parent {
    // current active menu's parent styles
}

You don't need to use jQuery.

Solution 2:[2]

Please try:

<script>
  jQuery(function($){  var cururl = window.location.href;                
  const urlarray = cururl.split("/");
var last = urlarray[urlarray.length-2]);
      
        $(".menu-item> a").each(function() {
       var pageurl = $(this).attr("href"); if(pageurl.indexOf(last) > -1){
        $(this).addClass("active");
        // $ (this).parent ("li").addClass ("active"); }
      })
  });
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Farzad
Solution 2