Set Active Class to Current PHP Page

Development is a lot quicker with PHP templates - header.php, footer.php, etc., since there is only one file dynamically included into each page. When there's only one header template that contains the primary menu, active classes need to be dynamically inserted.

A prior solution was to go into each page and manually insert a class for each link. In PHP, we can use a condition to check which page is currently active.


Create a PHP Variable

  • At the top of each page, set a variable to collect the URL path from the server.
<?php $page = basename($_SERVER['SCRIPT_NAME']); ?>
  • basename returns the URL path
  • $_SERVER is an array containing headers, paths, and script location information
  • SCRIPT_NAME contains the current script's path

Add PHP to the HTML Menu

  • PHP will check which page is currently set and attach the active class.
<nav>
     <li <?php if ($page == 'index.php') { ?>class="active"<?php } ?>><a href="index.php">Home</a></li>
     <li <?php if ($page == 'works.php') { ?>class="active"<?php } ?>><a href="works.php">Work</a></li>
     <li <?php if ($page == 'blog.php') { ?>class="active"<?php } ?>><a href="blog.php">Blog</a></li>
</nav>

Style the Active Class

nav ul li {
  list-style-type: none;
}
nav ul li a {
  text-decoration: none;
}
.active a {
  color: #28ADE6;
}