Jason Rowe

Be curious! Choose your own adventure.

PHP Active Tab Menu Pattern

I was just messing with PHP and made this simple little script to track which menu item is active. It looks at the last URL folder name to make the match. For example, if the URL was “http://localhost/example/About/” it would match “about” and write out the needed css. It also works correctly with the URL http://localhost/example/About/index.php by stripping off the index.php value and looking at the folder about.


< ?php

$folderName = basename($_SERVER&#91;'REQUEST_URI'&#93;);

if(strtoupper($folderName) == "INDEX.PHP")
{

$folderName = dirname ($_SERVER&#91;'REQUEST_URI'&#93;);
$paths = explode('/', $folderName);

foreach($paths as $key => $value)
{
if(!empty($value))
{
$new_paths[] = $value;
}
}

$last_path = $new_paths[count($new_paths) - 1];
$folderName = $last_path;
}

function getCSSName($str,$folderName)
{
//echo $str;
//echo $folderName;

if ($str == $folderName)
echo "current_page_item";
}

?>

Then a quick example of using it in the html.


<ul id="tabs">
<li class="home-item <?php getCSSName("EXAMPLE", strtoupper($folderName)); ?>">
<a rel="nofollow" title="home" href="http://localhost/example/">Home</a>
</li>
<li class="page-item-1 <?php getCSSName("ABOUT", strtoupper($folderName)); ?>">
<a title="About" href="http://localhost/example/About/">About</a>
</li>
<li class="page-item-2 <?php getCSSName("SERVICES", strtoupper($folderName)); ?>">
<a title="Services" href="http://localhost/example/services/">Services</a>
</li>
<li class="page-item-3 <?php getCSSName("CONTACT", strtoupper($folderName)); ?>">
<a title="Services" href="http://localhost/example/contact/">Contact</a>
</li>
<li class="page-item-4 <?php getCSSName("PICTURES", strtoupper($folderName)); ?>">
<a title="Services" href="http://localhost/example/pictures/">Pictures</a>
</li>
</ul>

<ul id=”tabs”>
<li class=”home-item <?php getCSSName(“AS”, strtoupper($folderName)); ?>”>
<a rel=”nofollow” title=”http://localhost/as/” href=”http://localhost/as/”>Home</a>
</li>
<li class=”page-item-1 <?php getCSSName(“ABOUT”, strtoupper($folderName)); ?>”>
<a title=”About” href=”http://localhost/as/About/”>About</a>
</li>
<li class=”page-item-2 <?php getCSSName(“SERVICES”, strtoupper($folderName)); ?>”>
<a title=”Services” href=”http://localhost/as/services/”>Services</a>
</li>
<li class=”page-item-3 <?php getCSSName(“CONTACT”, strtoupper($folderName)); ?>”>
<a title=”Services” href=”http://localhost/as/contact/”>Contact</a>
</li>
<li class=”page-item-4 <?php getCSSName(“PICTURES”, strtoupper($folderName)); ?>”>
<a title=”Services” href=”http://localhost/as/pictures/”>Pictures</a>
</li>
<li class=”rss”>
<a rel=”nofollow” title=”contact information 763-783-0708″ href=”contact”><b>Call Now 763.783.0708</b></a>
</li>
</ul>

Posted

in

by

Tags:

Comments

Leave a Reply

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