I have the following PHP script that will add a class of .Active to the current open page - this bit works but I am also trying to also add the page name to the body tag as an ID "#", but it does not seem to be working how I do it. Can anyone please advice me?
<!--add class .active to current page-->
<?php
$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 'class="active"';
}
}
?>
Here is the menu:
<li><a <?php href('index.php'); ?>>Home</a></li>
<li><a <?php href('about.php'); ?>>About</a></li>
<li><a <?php href('treatments.php'); ?>>Treatments</a></li>
And the HTML code:
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
It is very simple add that variable $page in echo
echo "class='active' id='$page'";
Basically, if you don't want to modify the template, you can't.
The solution would be to do this in your template, but it must be obvious to you:
<body <?php echo $id; ?>>
What seems less obvious to you, is just that you can't do this without touching the template.
Also, you should avoid global variables.