Drupal: A Hierarchical Taxonomic Trail
I want to generate a hierarchical palette from a taxonomy term (eg grandparent / parent / child) when I have a TID of "child". I've been tinkering with taxonomy_get_tree()
, but it's pretty hard to get by without very heavy iteration. There should be an easier way.
Thoughts?
Thank!
This is what I am doing:
$breadcrumb[] = l(t('Home'), NULL);
if ($parents = taxonomy_get_parents_all($tid)) {
$parents = array_reverse($parents);
foreach ($parents as $p) {
$breadcrumb[] = l($p->name, 'taxonomy/term/'. $p->tid);
}
}
drupal_set_breadcrumb($breadcrumb);
I usually use this in a function hook_view()
or hook_nodeapi($op="view")
.
source to share
The Breadcrumb taxonomy seems to provide this functionality.
If you don't want to use a module, the code can provide inspiration.
source to share
If you are using Drupal 7 the Breadcrumb taxonomy is still in dev version and you need to code.
A more complete solution could be the following (put this function in YOUR_THEME_NAME / template.php)
function YOUR_THEME_NAME_breadcrumb( $variables )
{
// init
$breadcrumb = $variables['breadcrumb'];
// taxonomy hierarchy
$hierarchy = array();
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)))
{
$tid = (int)arg(2);
$parents = array_reverse(taxonomy_get_parents_all($tid));
foreach( $parents as $k=>$v)
{
if( $v->tid==$tid ) continue;
$breadcrumb[] = l($v->name, 'taxonomy/term/'. $v->tid);;
}
}
// rendering
if (!empty($breadcrumb))
{
$output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';
$output .= '<div class="breadcrumb">' . implode("<span class='separator'>»</span>", $breadcrumb) . '</div>';
return $output;
}
}
source to share
function yourthemename_breadcrumb( $variables )
{// init
$breadcrumb = $variables['breadcrumb'];
// taxonomy hierarchy
$hierarchy = array();
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)))
{
$tid = (int)arg(2);
$parents = taxonomy_get_parents_all($tid); dpm($parents);
$parents = array_reverse($parents);dpm($parents);
$breadcrumb = array();
$breadcrumb[] = l('Home', '/');
foreach( $parents as $k=>$v)
{
$breadcrumb[] = l($v->name, 'taxonomy/term/'. $v->tid);;
}
}
// rendering
if (!empty($breadcrumb))
{
$output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';
$output .= '<div class="breadcrumb">' . implode("<span class='separator'>»</span>", $breadcrumb) . '</div>';
return $output;
}
}
source to share