0
votes

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 all 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?

3
You always pass condition $item == "Home" once in your loop, so class will always be set. So you'll need to change/expand your condition - Nathan Q
Can you post the output HTML? - Michael Berkowski

3 Answers

3
votes

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>";
}
1
votes

Try using

if($title == "Home")

rather than

if($item == "Home")

You were so close!

1
votes
$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.