Custom Drupal Breadcrumb for a cck content type

posted by Ishmael Sanchez on Nov 28, 2010

Drupal breadcrumbs are a pain. By default they aren't the usable breadcrumb navigation that people find helpful. On CCK node types they don't show any kind of site hierarchy; in fact by default they only show a link to the home page. The only place the breadcrumbs are helpful are on administrative pages. Yes, there are modules that help improve the breadcrumb system, but as a themer you can make it more usable with a few functions.

Output a custom breadcrumb

To do this we need to override the theme_breadcrumb function. If you don't have template.php file in your theme create one. Add to your template.php file the following function and clear your cache (change THEMENAME to the name of your actual theme).

/**
* Output a custom breadcrumb
*/
function THEMENAME_breadcrumb($breadcrumb) {
// We use strip_tags instead of check_plain to prevent outputting special characters
$title = strip_tags(drupal_get_title());
if (!empty($breadcrumb)) {
return '<div class="breadcrumb">'. implode(' / ', $breadcrumb). ' / ' . $title .'</div>';
}
// Otherwise, return an empty string.
return '';
}

Custom breadcrumb using a theme override
Shows the breadcrumb that is output using the theme override.

With the theme_breadcrumb function we are customizing it to append the node title to the end of the breadcrumb. This is a good start, but to make the breadcrumb more useful we need to define a hierarchy.

Generate a custom breadcrumb trail

Using a custom function we build a breadcrumb trail based off the node type. I'm adding a link to a view page to the trail for the articles node type on my site.

/**
* Generate a custom breadcrumb trail
*/
function THEMENAME_custom_breadcrumb($vars) {
$breadcrumb = array();

// Set home as the first item
$breadcrumb[] = l(t('Home'), '<front>');

// Add node types into breadcrumb trail
switch ($vars['node']->type) {
case 'article':
$breadcrumb[] = l(t('Articles'), 'articles');
break;
}
drupal_set_breadcrumb($breadcrumb);
return $breadcrumb;
}

Overwrite the breadcrumb variable

Now that we have our custom breadcrumb function we need to call it. Add the code below to the preprocess page function. We do a node type check because we only want to overwrite the breadcrumb with our custom function on certain node types. Otherwise if we didn't do this Drupal will simply discard it's default breadcrumb; meaning we would lose the default trail on admin pages.

function THEMENAME_preprocess_page(&$vars) {
if ($vars['node']->type == 'article') {
$vars['breadcrumb'] = theme('breadcrumb', ishalist_custom_breadcrumb($vars));
}
}

Custom breadcrumb trail
Final custom breadcrumb trail.

Resources

Post new comment

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.

Ishmael Sanchez