10 Dec 2016
Set Active Class to Current PHP Page
Development is a lot quicker with PHP templates - header.php, footer.php, etc., since there is only one file dynamically included into each page. When there's only one header template that contains the primary menu, active classes need to be dynamically inserted.
A prior solution was to go into each page and manually insert a class for each link. In PHP, we can use a condition to check which page is currently active.
Create a PHP Variable
- At the top of each page, set a variable to collect the URL path from the server.
- basename returns the URL path
- $_SERVER is an array containing headers, paths, and script location information
- SCRIPT_NAME contains the current script's path
Add PHP to the HTML Menu
- PHP will check which page is currently set and attach the active class.