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.

<?php
$page = 'aboutus';
include('header.php');
?>

/*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>
	<li class="menuitem <?php if($page=='contactus'){echo 'active';}?>" >
		<a href="contactus.php"><span>Contact Us</span></a>
	</li>  
	
</ul>

Hope it helps…

8 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.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>