Skip to content

Instantly share code, notes, and snippets.

@atelierbram
Last active April 25, 2017 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atelierbram/e79e696b96b862bf957de3a169e6f0bf to your computer and use it in GitHub Desktop.
Save atelierbram/e79e696b96b862bf957de3a169e6f0bf to your computer and use it in GitHub Desktop.
Set Active Class in PHP

... there are ways to do it (set an ‘active’ class based on page url) in PHP too. For anyone not using a framework that adds a class, here's a simple way to do it in PHP...

At the very top of the web page - above all HTML, even doctype;

<?php
  $pg = basename(substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],'.'))); // get file name from url and strip extension
?>

This will take a value of "about-us" from an URL that looks like www.mywebsite.com/about-us.php".

And to use it in a menu's li elements to add a class...;

<li class="<?php if($pg=='about-us'){?>active<?php }?>;">;
    <a href="/about-us.php">About Us</a>
</li>

The output on the "about-us.php" page when it is viewed in browser will look like this;

<li class="active">
  <a href="/about-us.php">About Us</a>
</li>
@atelierbram
Copy link
Author

Taken from here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment