How can add active class for multi-dimensional array of menus.

How can add active class for multi-dimensional array of menus. I am trying to create a menu where a class “active” is assigned to the page whenever

following the step by step using php

1) Create a multi-dimensional array of menus.

2) Key is the link and value is the text.

3) Get the current page URL.

4) Get the last segment of the url using basename().

5) That will be your current page variable. If its blank, assign it to home page.

6) Loop over menus array.

7) Display menu lis in loop.

8) If current loop items is equal to current page, add class active else, add no class.

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
$menus = array();
$menus['main'] = 'index.php';
$menus['news'] = 'News';
$menus['contacts'] = 'Contacts';
$currentURL = curPageURL();// Get Current url here.
$currentPage = basename($currentURL);
$currentPage = empty($currentPage) ? 'main' : $currentPage;
if (! empty($menus)) {
?>
<ul class="nav navbar-nav">
<?php
    foreach ($menus as $lnk => $txt) {
        $activeCls = ($lnk == $currentPage) ? 'active' : '';
?>
     <li class="<?php echo $activeCls;?>"><a href="http://localhost/wp/<?php echo $lnk;?>"><?php echo $txt;?></a></li>
    <?php
    }
?>
</ul>
<?php
}
?>

I think you are looking for this. Tried and tested

    $(".navbar-nav").find("a").click(function(){

               $(".navbar-nav").find("li").removeClass("active");
                $(this).parent("li").addClass("active");




        })

        $( window ).load(function() {


         var which_page=window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
                    $(".navbar-nav").find("a").each(function(){
                    if($(this).attr("href") == which_page)
                    {
                     $(this).addClass("active");

                    }

                   })



        });
Social Share

Leave a Comment