I have a jQuery way of adding a .current class to an anchor link based on the site url and the corresponding page (i.e., if I’m on the “about” page, it’ll add a .current class to the anchor link in the nav menu that directs to “about.php”). It definitely does the job, and it’s super simple, but I wanted a PHP way to accomplish this, in a similar fashion that WordPress does. What I ended up with is something that is sort of unconventional and not easily modifiable (code below)
My question is: Is there an easier way of doing this? You’ll see in my code that I have to assign a variable $nav[#] to each anchor link.. it’s not the most convenient of things…
The HTML:
<ul class="nav">
<li><a href="index.php" class="<?php echo $nav1; ?>">home</a></li>
<li><a href="publications.php" class="<?php echo $nav2; ?>">publications</a></li>
<li><a href="research.php" class="<?php echo $nav3; ?>">research</a></li>
<li><a href="cv.php" class="<?php echo $nav4; ?>">cv</a></li>
<li><a href="contact.php" class="<?php echo $nav5; ?>">contact</a></li>
</ul>
The PHP:
<?php
function getUrl() {
$url = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
$myurl = getUrl() ; // As was suggested, I could also just set $myurl = $_SERVER['PHP_SELF'] and avoid the complicated function call
$split_url = explode("/" , $myurl) ;
$page = end($split_url) ;
$nav1 = $nav2 = $nav3 = $nav4 = $nav5 = ' ' ;
if ( $page == "publications.php" )
$nav2 = 'current' ;
else if ( $page == "research.php")
$nav3 = 'current' ;
else if ( $page == "cv.php" )
$nav4 = 'current' ;
else if ( $page == 'contact.php')
$nav5 = 'current' ;
?>
Take a look at
$_SERVER['PHP_SELF']. It will give the file name of the current file being served.Here’s a function that will add the current class if the page matches the
$_SERVER['PHP_SELF'].Usage would be as follows.
If you wanted to really make it special you could do something like this.