Create Dynamic Navigation Menus
Use PHP to build a navigation menu widget that works consistently across your site.
Writing the navigation menu for your site can be a pain. You don’t want to write the same code over and over on every page. Ideally, you would have a PHP menu function that would render the menu with the current page highlighted. This hack gives you that simple menu function (for the low cost of this book, no less!).
The Code
Save the code in Example 1, which demonstrates the use of menu.php as index.php.
Example 1. Using the menu library
|
Page: |
Example 2 shows the library, which is surprisingly simple.
Example 2. Making everything work with the PHP library, menu.php
.menu-inactive, .menu-active {
padding: 2px;
padding-left: 20px;
font-family: arial, verdana;
}
.menu-inactive { background: #ddd; }
.menu-active { background: #000; font-weight: bold; }
.menu-inactive a { text-decoration: none; }
.menu-active a { color: white; text-decoration: none; }
index.php creates the menu by calling the page_menu function and specifying the page ID. The ID of the page is used to decide which menu item is selected. The index.php script also calls the menu_css function to set up the CSS styles for the menu.
You can change the makeup of the menu by altering the bottom portion of the menu.php file to add or remove menu items. You can also change the look and feel of the menu by altering the CSS class definitions in the menu_css function.
