mattroberts33
mattroberts33

Reputation: 280

How to use PHP to display active class on sub nav links?

I have PHP code to display the active class on links in the nav, but I'm having trouble finding a solution to applying the active class properly for the sub nav - that being the pages that are in folders outside of the root directory. Here is the code that I have!

Here is the example code: (it works on the real code)

<?php
    $current_page = basename($_SERVER['PHP_SELF']);
?>

This is an example for a stand alone nav link:

<li class="<?php if ($current_page == "index.php"){ echo "active "; }?> item"><a href="index.php">Home</a></li>

This is an example for the drop down menu:

<li class="<?php if ($current_page == "index.php"){ echo "active "; }?> item has-dropdown"><a href="about.php">About Us</a>...

Now the code for the sub nav's so far isn't working for me, but here it is with the real code!

<?php 
    $cp = basename($_SERVER['PHP_SELF']);
    $cf = dirname($_SERVER['PHP_SELF']);
?>

Here is an example for a stand alone nav link:

<li class="<?php if ($cp == "index.php"){ echo "active "; }?> item"><a href="/index.php">Home</a></li>

Here is an actual drop down menu from my nav.

<li class="<?php if ($cp == "courses.php" || $cp == "oshawa.php" && $cf == "courses" || $cp == "bowmanville.php" && $cf == "courses"){ echo "active "; }?> item has-dropdown">
    <a href="/courses.php">Courses</a> <!-- COURSES -->
    <ul class="dropdown">
        <li><a href="/courses.php">Courses</a></li>
        <li><label>Locations</label></li>
        <li><a href="/courses/oshawa.php">Oshawa</a></li>
        <li><a href="/courses/bowmanville.php">Bowmanville</a></li>
    </ul>
</li>

This specifically is where the code breaks, the first part works fine, but the second we add the && $cf == "courses" it breaks.

$cp == "oshawa.php" && $cf == "courses" 

I don't think it's a formatting issue, I think it's just the code itself, not sure where to go from here. I'm not very good with PHP, all help is appreciated, thanks =)

Upvotes: 2

Views: 900

Answers (1)

Ravi Dhoriya ツ
Ravi Dhoriya ツ

Reputation: 4414

Try this, (Assuming your all courses pages exist in courses directory itself.)

<?php 
    $cp = basename($_SERVER['PHP_SELF']);
    $cf = dirname($_SERVER['PHP_SELF']);
?>

<li class="<?php if ($cp == "courses.php" || $cf == "/courses"){ echo "active "; }?> item has-dropdown">
    <a href="/courses.php">Courses</a> <!-- COURSES -->
    <ul class="dropdown">
        <li><a href="/courses.php">Courses</a></li>
        <li><label>Locations</label></li>
        <li><a href="/courses/oshawa.php">Oshawa</a></li>
        <li><a href="/courses/bowmanville.php">Bowmanville</a></li>
    </ul>
</li>

Upvotes: 2

Related Questions