How to set current page active when menu in php file

Active menu item is simple when we go with HTML but when we develop website through PHP, its little bit difficult. As in HTML we can simply call active class for each menu label, here we need to write some dynamic CSS, here our hope/clue is URL . Based on URL we can do some magic. Lets assume we have class called "current" and we want this class active based on page we areee...


Code is simple look how i convert,




<ul id="menu" >

          <li class="activemenu"><a title="Home" href="index.php">Home</a></li>

          <li class="activemenu"><a title="About us" href="about-us.php">About us</a></li>

          <li class="activemenu"><a title="services" href="services.php">Services</a></li>

          <li class="activemenu"><a title="Security Doors" href="security-doors.php">Security Doors</a></li>

         

          <li class="activemenu"><a title="Gallery" href="gallery.php">Gallery</a></li>

          <li class="activemenu"><a title="Contact Us" href="contact.php">Contact Us</a></li>

        </ul>


Dynamic CSS Menu reading page URL


<ul id="menu" >

          <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'activemenu'; }else { echo ''; } ?>"><a title="Home" href="index.php">Home</a></li>

          <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about-us.php'){echo 'activemenu'; }else { echo ''; } ?>"><a title="About us" href="about-us.php">About us</a></li>

          <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'activemenu'; }else { echo ''; } ?> activemenu"><a title="services" href="services.php">Services</a></li>

          <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'security-doors.php'){echo 'activemenu'; }else { echo ''; } ?>"><a title="Security Doors" href="security-doors.php">Security Doors</a></li>

         

          <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'gallery.php'){echo 'activemenu'; }else { echo ''; } ?>"><a title="Gallery" href="gallery.php">Gallery</a></li>

          <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'activemenu'; }else { echo ''; } ?>"><a title="Contact Us" href="contact.php">Contact Us</a></li>

        </ul>


Now you can call your menu <?php include 'menufilename.php';?> on any php page.

No comments: