The following PHP function add class="active" to the current page open.
<?php #add class .active to current page
$directoryURL = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURL, PHP_URL_PATH);
$components = explode('/', $path);
$currentPage = preg_replace("/\\.[^.\\s]{3,4}$/", "", end($components));
if ($currentPage == "") {
$currentPage = "index";
}
function href($url) {
global $currentPage;
$path = explode('/', $url);
$page = preg_replace("/\\.[^.\\s]{3,4}$/", "", end($path));
echo 'href="' . $url . '"';
if ($page == $currentPage) {
echo 'active';
}
}
?>
Here is the menu items:
<li><a class="icon-glass"<?php href('index.php');?>>Home</a></li>
<li><a <?php href('about.php');?>>About</a></li>
The problem is, that function only works with menu items that has no class="" declared, ie:
<li><a <?php href('about.php');?>>About</a></li>
And it does not work for this one:
<li><a class="icon-glass"<?php href('index.php');?>>Home</a></li>
I believe it is something to do with this part of the script:
if ($page == $currentPage) {
echo 'class="active"';
}
The question: How do I keep it do what it does now, which is adding class=""
when it is not already added, BUT also just add the .active
bit inside an already existed class (if found)?
I tried to only use echo 'active';
but that didn't work.
Try this format with existing php code
<li><a class="icon-glass <?php href('index.php');?>">Home</a></li>
<li><a class="<?php href('about.php');?>">About</a></li>
Means you have to echo the class active inside class property double quotes "".
Replace function href with
function href($url) {
global $currentPage;
$path = explode('/', $url);
$page = preg_replace("/\\.[^.\\s]{3,4}$/", "", end($path));
if ($page == $currentPage) {
echo ' active " ';
}else{
echo ' " ';
}
echo ' href="' . $url . '" ';
}
And this html
<li><a class="icon-glass"<?php href('index.php');?>>Home</a></li>
<li><a <?php href('about.php');?>>About</a></li>
with
<li><a class="icon-glass <?php href('index.php');?>>Home</a></li>
<li><a class="<?php href('about.php');?>>About</a></li>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.