0

I have this category menu. When I click on a category menu item, it opens the category page and what I need it to add the 'active' Bootstrap class on the menu item that was selected (clicked).

How can I do it?

<?php      
 $cat = "SELECT * FROM category WHERE cat_parent_id = :value ORDER BY cat_id ASC"; 
   $stmt = $con->prepare($cat);
   $stmt->bindValue(':value', 1, PDO::PARAM_STR);
      $stmt->execute(); 
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
          extract($row);
             $name_cat = str_replace("-"," ", $cat_name);
             $name_under = str_replace(" ","-", $cat_name);
             ?>     
               <li><a class="dropdown-item" href="<?php echo $home_url . 
                $cat_id."/".strtolower($name_under);?>.html"><?php echo strtoupper($name_cat); ?></a> 
                 </li>
<?php } ?>  
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ogum
  • 379
  • 1
  • 8
  • 24
  • Compare the `href` url to the [current url](https://stackoverflow.com/questions/6768793/get-the-full-url-in-php). – El_Vanja Jan 28 '21 at 17:44

1 Answers1

0

Going an extra step on the comment above from @El_Vanja:

Figure out the current url with the following code:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Then add that condition when you're forming the link:

<li<?php if($home_url == $actual_link echo ' class="active"';?>><a class="dropdown-item" href="<?php echo $home_url . 
            $cat_id."/".strtolower($name_under);?>.html">
            <?php echo strtoupper($name_cat); ?></a></li>
Paulo Hgo
  • 834
  • 1
  • 11
  • 26
  • You might want to remove the link all together for the "active" page – Paulo Hgo Jan 28 '21 at 23:05
  • $home_ur and $actual_link are not the same. doesn't work. Example: $home_url = http://localhost/site-name/, $actual_link = http://localhost/site-name//2/page.html (there is a htaccess rule) – Ogum Jan 29 '21 at 09:30