PHP Menu Highlighter

PHP Menu Highlighter – highlight current page in your navigation menu.

While developing a website recently, I realized I had already produced the navigation menu in a PHP file and used the include function to pull it into each page, so I needed a way to highlight the current page’s navigation menu item:

This uses the nth-child(x) property of CSS to target menu item # x, where x is your navigation menu item in an array. Let’s say you have the following menu:

<ul class="navigation">
 <li>Home</li>
 <li>About</li>
 <li>News</li>
</ul>

In PHP you set up an array, like so:

$menuitems = [
 "home" => 1,
 "about" => 2,
 "news" => 3,
 ];

And now that numbers are assigned to each navigation menu item, we can specifically target each menu item using li:nth-child and override linked stylesheets with inline CSS.

Create our PHP function, we’ll call it “highlight”:

<?php
 function highlight($index)
 {
   $menuitems = [
   "home" => 1,
   "about" => 2,
   "news" => 3,
   ]; // You can put these all on one line

echo "
 <style>
   ul.navigation > li:nth-child(" . $menuitems[$index] . ") {
   background-color: #B8C7CF;
   }
 </style>
 ";
 } // end of function
?>

Save this to “highlight.php”
Then use the function on each page. For example, in the “home.php” page, we would use the highlighter like this:

<?php include 'highlight.php' ?>
<?php highlight("home"); ?>

Effectively, “home” is 1 in the array, so the html code written by the highlighter produces li:nth-child(1), which is a way to target the first <li> item in a series of list items.

So this will use CSS to highlight the menu item by way of PHP.

Note: If you are using separators between your navigation menu items, you’ll have to adjust the numeric values of each menu item accordingly.

Note: If you have <a> links in your list menu, your function should target the links like so: li:nth-child(x) > a .