Theme Breadcrumb Manipulation

Recently we ran into a theme problem in Drupal 6 where the client wanted the breadcrumb to reflect different states based on where the user came from. Some pages were tagged with multiple taxonomy terms, so the breadcrumb "should" look different based on which section of the site the user came from.

What we decided to do is serve the breadcrumb based on $_SERVER['HTTP_REFERER']. Here is the hook function in our template.php file we used:

/**
 * Implements theme_breadcrumb()
 * Return a themed breadcrumb trail.
 *
 * @param $breadcrumb
 *   An array containing the breadcrumb links.
 * @return a string containing the breadcrumb output.
 */
function <theme_name>_breadcrumb($breadcrumb) {

  if (!empty($breadcrumb)) {
    // uncomment the next line to enable current page in the breadcrumb trail
    $page_title = drupal_get_title();
    if (!isset($breadcrumb['title']) && !empty($page_title)) {
      $breadcrumb[] = strip_tags(drupal_get_title());
    }

    //now fix pages that have multiple taxonomy terms, overwrite with referer
    $breadcrumbfixed = $breadcrumb;
    $overwrite = '/maps/'; //a unique directory or identifier in the url where you want this rule to apply
    $overwriteshort = substr($overwrite, 1);
    $pos = strpos($_SERVER['HTTP_REFERER'], $overwrite);
    if ($pos !== FALSE) {
      $terms = explode($overwrite, $_SERVER['HTTP_REFERER']); 
      $term = $terms[count($terms)-1];
      $pathlook = drupal_lookup_path('source', $overwriteshort . $term);
      if ($pathlook !== FALSE) {
        $nodearr = explode('/', $pathlook);
        $node = node_load($nodearr[1]);
        $breadcrumbfixed[2] = l($node->title, $node->path);
      } else {
        //drupal could not find a valid path for the REFERER
      }
    }
    //now overwrite breadcrumb with breadcrumbfixed
    $breadcrumb = $breadcrumbfixed;

    return '<nav class="breadcrumb">' . implode(' > ', $breadcrumb) . '</nav>';
  }
}

The Drupal function drupal_lookup_path ended up being very useful. You can hand it the displayed url or the internal url to get the information you need.

Code

Read This Next