Highlight currently active menu item.

How do I show the user what page they are on.?
If you want to show your user which page is currently active you may want to highlight an item in your menu.

It is quite simple to highlight the currently active link in your menu. It is done with two very simple lines of php.
But first you will need a menu to work with…like this…

<ul>
<li><a href="link1.html">1</a></li>
<li><a href="link2.html">2</a></li>
<li><a href="link3.html">3</a></li>
</ul>

We have a simple menu that you can apply styles to. We won’t go into that just now. Let’s concentrate on the php for now. So now we add a simple line of php to each of our menu links.
Here is the php you’ll need to add…

<?php if($current == '1') {echo 'class="current"';} ?>

Look at the line of php above. See where it says $current == ‘1’. You can replace the ‘1’ with any name you like. For example $current == ‘home’.
Add the line of php to your menu inside the <li> tag like this…

<ul>
<li<?php if($current == '1') {echo 'class="current"';} ?> ><a href="link1.html">1</a></li>
<li><a href="link2.html">2</a></li>
<li><a href="link3.html">3</a></li>
</ul>

You will need to add the same line of php to each menu item inside the <li> tags. Remember to change the $current == ‘1’ to something unique for each link.

<ul>
<li<?php if($current == '1') {echo 'class="current"';} ?> ><a href="link1.html">1</a></li>
<li<?php if($current == '2') {echo 'class="current"';} ?> ><a href="link2.html">2</a></li>
<li<?php if($current == '3') {echo 'class="current"';} ?> ><a href="link3.html">3</a></li>
</ul>

Look at the code above. Do you see where it says class=”current”. You can change the word “current” to anything you want. This name will be the class name that you create in your css file. This class is what you will use to change the appearance of your menu item.
Final step
You should now have a menu like the one above and a new class in your css file that you will use to style the currently active link.

The final step is to add one more line of code to each of your pages that will tell your menu which item should be highlighted.
Add the following line of code just after the <body> tag.

<body>
<?php $current = '1';?>

Look at the code above. Where it says $current = ‘1’. Make sure you match the ‘1’ with what you have in your menu. So, for example, if you have chosen to use $current == ‘home’ for the first item in your menu then on your “home” page you would also have $current = ‘home’.

Leave a Comment