PHP Header Include Navigation Menu Issues
I am using a PHP include to input my header, which of course, contains my navigation menu.
The 'header.php' code for the navigation menu part is below:
$nav = array("Home","About","Portfolio","Products","Services","Contact");
foreach($nav as $item)
{
$class = '';
$href = $item;
if($item == "Home")
{
$class = 'class="current-menu-ancestor parent"';
$href = 'index';
}elseif($item == $title){
$class = 'class="current-menu-ancestor parent"';
}
echo "<li $class><a href='$href.php'>$item</a></li>";
}
Sorry if its a bit messy.
It gets $title
from the relevant page, example code that would be displayed on a page is:
$title = "Home";
include("header.php");
Now it al开发者_运维技巧l seems to work fine, the right navigational menu items are there, they all link to right places etc, 'home' is in fact 'index.php' not 'home.php' as coded in 'header.php' above.
When on the 'home' page, the 'home' page nav menu item is highlighted as it should be to indicate that the user is on that page, however, when I go to any other page, say for example the 'about' page, it highlights the 'about' nav menu item and also the 'home' nav menu item.
Where am I going wrong?
Your foreach loop will always place the $class for "Home" as "current-menu-ancestor", assuming that's what makes it highlighted.. You might want to do something like below:
foreach($nav as $item)
{
$class = '';
$href = $item;
if($item == "Home")
{
// $class = 'class="current-menu-ancestor parent"'; Get rid of this
$href = 'index';
}
if($item == $title) // Change this to if instead of elseif
{
$class = 'class="current-menu-ancestor parent"';
}
echo "<li $class><a href='$href.php'>$item</a></li>";
}
Try using
if($title == "Home")
rather than
if($item == "Home")
You were so close!
$nav = array("Home","About","Portfolio","Products","Services","Contact");
foreach($nav as $item){
$class = '';
$href = $item;
if ($item == "Home") {
$href = 'index';
}
if ($item == $title) {
$class = 'class="current-menu-ancestor parent"';
}
echo "<li $class><a href='$href.php'>$item</a></li>";
}
Is the correct code. It was just a little mixup in your conditional logic.
精彩评论