Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Using PHP to change class name of list item

I am currently working on a project and I am using PHP for the header and footer.

I want to change the class name of the list items for the nav bar that I have included in the header.php file.

I need to change the class to "active" when it is on that page so I do not have to write css for each page to change the active state of of the nav bar item.

I just need to change the li not the ul class.

the li only needs to have class="active" when it is on the specific page

<ul id="nav">
    <li>home</li>
    <li class="active">about</li>
</ul>

just an example. I need to set the class for home to active when on the home page and remove the class from about when on the home page and vice-a-versa.

2 Answers

Before you include the header into your page, create a variable called "$page" and give it a value like "home" or "about" then use conditional statements such as the example below in your header.

<ul id="nav">
    <li>home</li>
    <li class="<?php if ( $page == "About" ) { echo "active"; } ?>">about</li>
</ul>

Hi Ted,

Here is an example from one of Treehouses' courses.

// This is a snippet from header.php which is an include file
<ul class="nav">
        <li class="shirts <?php if ($section == "shirts") { echo "on"; } ?>"><a href="shirts.php">Shirts</a></li>
        <li class="contact <?php if ($section == "contact") { echo "on"; } ?>"><a href="contact.php">Contact</a></li>
        <li class="cart"><a target="paypal" href="https://www.paypal.com/cgi-bin/webscr?cmd=_cart&amp;business=Q6NFNPFRBWR8S&amp;display=1">Shopping Cart</a></li>
      </ul>

At the top of each file, shirts.php and contact.php, are variables $section = "shirts" and $section = "contact" respectively.

Jeff