3.9. Creating Navigation That Does Not Link to Itself

Problem

You need to add a menu of links to several related pages, but want to leave off the link to the current page being viewed.

Solution

Use a PHP or JavaScript function on each page to match the address of the current page in a list of related pages. Then build the menu from the list, leaving off the link for the matched address.

Discussion

Some simple scripting can eliminate the need to create and maintain individual, hand-coded menus on each page. In both the PHP and JavaScript versions, you will create arrays for the page addresses and link text, and then use a for loop to compare each address value to that of the current page and build the code for the menu. The PHP code concerns three related pages titled Purple, Green, and Orange:

	<?
	$color_urls = array('/colors/purple.php',
	                     '/colors/green.php',
	                     '/colors/orange.php');
	$color_links = array('Purple',
	                     'Green',
	                     'Orange');

First, you will assign the values you want to use for your menu in the two arrays, making sure the link paths ($color_urls) and link names ($color_links) are listed in the same order. The rest of the code contains the function makeMenu that builds the menu.

	function makeMenu($urls,$links) {
	$full_path = getenv("REQUEST_URI");
	 for ($i = 0; $i < sizeof($links); $i++) {
	  if (!strstr($full_path,$urls[$i])) {
	   $menu .= '<p><a href="'.$urls[$i].'">'.$links[$i].'</a></p>';
	  } else {
	   $menu .= '<p>'.$links[$i].'</p>';
	  }
	 }
	 echo $menu;
	 }
	 ?>

The function expects two parameters: ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.