Simple PHP Navbar
Wednesday, April 30, 2008
While working on a simple website that didn't need any kind of CMS with it, I came up with a very simple way of creating a dynamic navigation bar with PHP. The code is pretty simple, but I've always done this manually before and this just makes it simple. So here it is.
First we create a function in PHP:
function createNav($title, $link){
if("/".$link == $_SERVER['PHP_SELF']){
return "<li id=\"current\">".$title."</li>\r";
}else{
return "<li><a href=\"".$link."\">".$title."</a></li>\r";
}
}
And then this is how you call it:
echo createNav("Home","index.php");
So if you are on the page that navigation button relates to it will give you <li id="current">Home</li>. If you're on any other page, it gives you <li><a href="index.php">Home</a></li>.
Easy enough. So just call that for each button you need between your <ul> tags:
<ul>
<?php
echo createNav("Home","index.php");
echo createNav("About","about.php");
echo createNav("Products","products.php");
echo createNav("Contact","contact.php");
?>
</ul>
I know it's nothing spectacular, but it sped up the coding process for me once I figured it out, and it will certainly be a lot faster in the future if anything needs to be changed or added.