This is an archive site. For the recent posts, visit orderedlist.com.

Ordered List

OrderedList

Mar 8 2005

Breadcrumb Trails

This is an idea I borrowed from a popular ecommerce system, OSCommerce. This is not the exact class, but I need to give idea credit where it is due. I simplified and rewrote the class for my usage.

class Breadcrumb {

  var $home;
  var $trail;

  function Breadcrumb() {
    global $client_name;
    $home = array('title' => 'YourSite.com',
            'url' => 'http://www.yoursite.com/');
    $this->home = $home;
  }

  function drop_crumb($title, $url = NULL) {
    if ($title) {
      $this->trail[] = array('title' => $title, 
            'url' => $url);<br />
    }
  }

  function print_trail($separator = '&laquo;') {
    $output = '&lt;a href="' . $this->home['url'] . '"&gt;;' . 
                $this->home['title'] . '&lt;/a&gt;';
    foreach($this->trail as $crumb) {
      $output .= ' ' . $separator . ' ' . 
                ($crumb['url'] ? '&lt;a href="' . 
                $this->home['url'] . $crumb['url'] . '"&gt;' .
                $crumb['title'] . '&lt;/a&gt;' : $crumb['title']);
    }
    return $output;
  }
}

Explanation

The class sticks with two main variables: $home and $trail. The $home variable holds the root url and name of your site, the ‘Home’ link. The $trail variable uses an array to store the title and url of the links in the breadcrumb trail. The Breadcrumb function is run when the class is created, setting the $home variable to the specified values. To add crumbs to the trail, you use the drop_crumb function, including the Title and, optionally, the URL of the crumb. If no URL is specified, the crumb is displayed as text only with no link. This is useful to show current position without duplicating link references. The print_trail function is used just as you would assume; to output the trail to a string.

Usage

$bread_trail = new Breadcrumb;

$bread_trail->drop_crumb('Examples','examples/');
$bread_trail->drop_crumb('BreadCrumb Trail');

echo $bread_trail->print_trail();