



In this article we will see how PHP can be used to generate a navigation menu which doesn't link to the current page, is up to date on every page and only shows section relevant links in the sub menu.This is one of the core features of a Content Management System (CMS) so anyone interested in developing their own CMS might be interested in this article.
Author: Phil Smears
Date added: 3rd January 2007
Apart from displaying system state using classes and the <strong> element it can be difficult to keep a navigation menu up to date and displaying links to newly added pages. The same include file, with a little modification to ensure all the sub menus are displayed, can be used to generate a site map. Incidentally an error page for mistyped urls also can use the include to generate a site map. This means we'll never have to worry again whether the navigation menu is up to date on all sections of the site.
Obviously a link to an include file on every page can be used to generate a menu, but how can the same include file only show section relevant links and insert 'parent' and 'current' classes on the appropriate elements? Here's how:
We'll start by creating one array which holds every page, link URL and link text:
Here is the array for the navigation menu used by this site before we moved it over to Drupal.
A mixture of index and associative arrays was used basically for readability. Every time a page was added to the site it was inserted in the array in the correct place and that was it - we didn't need to worry about updating anything else.
The PHP script that acted on the array was a little more complicated.
It started by looping through the first level of the array outputting each link in a list element. Whilst it was looping through each element of the array, it checked whether the 'url' element in the array corresponded to the page's current URL and if so added a 'current' class. It also checked whether there was a sub menu and whether it should be displayed or not. For example we only wanted to display the 'Articles' sub menu containing 'PHP Navigation Menus' and 'Flexible images with CSS' if a visitor was in the 'Articles' section of the site. A similar include operated on the sub menu, again checking if it in turn has a sub menu, in which case a final include loops through third level navigation items in much the same way. It ends there as we took a decision to limit depth to three levels otherwise, content would have just been buried too deep.
Section pages needed a variable to let the script know which section the current page belongs to. Each page had something like <? $section="Articles"; ?> near the top of the page in the code.
I think if we had gone on to improve it we would have developed a script which just scanned the directory structure and built a menu using that structure. As it was we decided to move over to Drupal so that more people could be allowed to edit the site including those without coding skills.