[英]Working with PHP_SELF
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.
我需要根据用户是否在相应页面上将类添加到A标签。 So to clarify, here is the code:
所以要澄清,这是代码:
<?php
$basename = substr(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. 如您所见,取决于用户是使用index.php还是about.php,将插入class = current。 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
正常工作正常,但是我在Wordpress中使用以下代码,其中所有页面都是这种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. 因此,关于页面的URL是index.php?page_id = 9,这意味着它将始终将类输入索引1。 Only solutions that I know of is that the
$basename == 'index'
can in anyway be full URL, eg $basename == 'index.php?page_id=X'
but I couldnt make that work. 我所知道的唯一解决方案是
$basename == 'index'
无论如何都可以是完整的URL,例如$basename == 'index.php?page_id=X'
但我无法做到这一点。
Help! 救命! Note that I am not experienced with PHP so any replies with detail would be appreciated!
请注意,我对PHP没有经验,所以任何详细的答复都将不胜感激!
the current file: __FILE__
当前文件:
__FILE__
the current folder of your file dirname(__FILE__).DIRECTORY_SEPARATOR // in 5.3: __DIR__
文件
dirname(__FILE__).DIRECTORY_SEPARATOR // in 5.3: __DIR__
的当前文件夹dirname(__FILE__).DIRECTORY_SEPARATOR // in 5.3: __DIR__
$page = $_GET[page_id];
我相信如果网址是?page_id = 9,这将返回例如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. 考虑到您使用的是Wordpress,建议您在页面顶部进行一个变量,以确定该页面的当前位置。
$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></a>
,如下所示:
<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 附加信息: 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
> >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.