how to highlight the current page in menu in php

This is one of the first problems faced by new-by developers when moving to php from static html pages. How to highlight the current page in menu? How to highlight the current page navigation in header.php?

In a HTML website you have separate pages and in each page you assign a css class of ‘active’ or ‘current’ to the link of current page in main menu. Now, in php you split the entire html into different pages like header.php, page.php, footer.php etc.. So your navigation goes into header.php. The question comes how to recognize in header.php that which page is being viewed?

A simple way to do it is:

1) Declare a variable in your pages(e.g: aboutus.php, cotactus.php) just before including header.php or menu.php whichever file your navigation markup is in.

$page = 'aboutus';

/*rest of your page content follows */

2) Now in your header.php you read the value of this variable to determine which is the page being viewed and accordingly you assign a different/additional css style to its navigational link.

<ul class="mainmenu" >
	<li class="menuitem <?php if($page=='aboutus'){echo 'active';}?>" >
		<a href="aboutus.php"><span>About Us</span></a>
	<li class="menuitem <?php if($page=='contactus'){echo 'active';}?>" >
		<a href="contactus.php"><span>Contact Us</span></a>

Hope it helps…

Published by

Chandan Chaudhary

Chandan is a WordPress guy. A programmer at heart. He loves building community sites with WordPress and BuddyPress.

17 thoughts on “how to highlight the current page in menu in php”

  1. Thanks! Worked great 🙂 I just had to remove the space between ‘menuitem’ and ‘<?php if($page==’aboutus’){echo ‘active’;}?>’.

    1. I am not sure why you had to remove that space. I’d put that space deliberately since i want class as ‘menuitem active’ (2 classes) and not ‘menuitemactive’.

  2. Thank you so much. I am learning PHP and it’s very helpful for me. I was thinking to get it done with database by collecting id. But it is very cleaver and beautiful to have a global variable for every page. Thanks again for this.

  3. Thank you so much! I’m just teaching myself PHP basics this week and I ran into this exact problem. You explained it clearly enough for my beginner self 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *