Page 1 of 1

PHP Active menu

Posted: Sat Nov 21, 2020 10:45 pm
by info_pi7b40vs
https://css-tricks.com/forums/topic/dyn ... tive-menu/
@beverleyh thanks! :D

Yep, there are ways to do it in PHP too. For anyone not using a framework that adds a class, here’s a simple way to do it in PHP…

At the very top of the web page – above all HTML, even doctype;

<?php
$pg = basename(substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],'.'))); // get file name from url and strip extension
?>


This will take a value of “about-us” from an URL that looks like “www.mywebsite.com/about-us.php”.

And to use it in a menu’s li elements to add a class…;

<li class="<?php if($pg=='about-us'){?>current<?php }?>">
<a href="/about-us.php">About Us</a>
</li>
<li class="<?php if($pg=='services'){?>current<?php }?>">
<a href="/services.php">Services</a>
</li>


The output on the “about-us.php” page when it is viewed in a browser will look like this;

<li class="current">
<a href="/about-us.php">About Us</a>
</li>
<li class="">
<a href="/services.php">Services</a>
</li>