Apologies for the bad title. I need a class to be added to an A tag depending on if the user is on respective page. So to clarify, here is the code:
<?php
$basename = sub开发者_Go百科str(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4);
?>
And then I use this code in the menu:
<li><a href="index.php"<?php if ($basename == 'index') { echo ' class="current"'; } ?>>Home</a></li>
<li><a href="about.php"<?php if ($basename == 'about') { echo ' class="current"'; } ?>>About</a></li>
As you can see, depending on if the user is on index.php or about.php, the class=current will be inserted. This works fine normally, but I am using this code in Wordpress where all the pages are this type of URL: index.php?page_id=X
So the about page URL is index.php?page_id=9, meaning that it will always input the class into the index one. Only solutions that I know of is that the $basename == 'index'
can in anyway be full URL, e.g. $basename == 'index.php?page_id=X'
but I couldnt make that work.
Help! Note that I am not experienced with PHP so any replies with detail would be appreciated!
the current file: __FILE__
the current folder of your file dirname(__FILE__).DIRECTORY_SEPARATOR // in 5.3: __DIR__
$page = $_GET[page_id];
I believe this will return for example 9 if the url is ?page_id=9
Considering you're using Wordpress, I'd suggest that you make a variable towards the top of your page that determines that page's current location.
$path_parts = pathinfo($_SERVER['PHP_SELF']);
$current = strtolower($path_parts['filename']);
Then take that variable and set it in the <a></a>
, as such:
<a <?php if($current == 'about') echo 'class="current"'; ?> href="#">About</a>
Or something like this, it's a start anyway.
additional information: http://php.net/manual/en/function.pathinfo.php
function GetFileName()
{
$currentFile = basename($_SERVER["PHP_SELF"]);
$parts = Explode('.', $currentFile);
return $parts[0];
}
$basename = GetFileName();
<li>
<a href="index.php" <?php if($basename =="index") echo "class='current'"; ?>>Home</a>
</li>
<li>
<a href="about.php" <?php if($basename =="about") echo "class='current'"; ?>>About</a>
</li
>
精彩评论