I'm looking to generate a hierarchical breadcrumb from a taxonomy term (e.g. grandparent/parent/child) when all I have is the TID of "child". I've been toying around with taxonomy_get_tree()
, but it seems quite difficult to do without very heavy iteration. There has to be an easier way.
Thoughts?
Thanks!
This is what I do:
$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'll typically stick this in a hook_view()
function or hook_nodeapi($op="view")
function.
Taxonomy Breadcrumb seems to provide this functionality.
If you don't want to use the module, the code might provide inspiration.
If you are using Drupal 7, Taxonomy Breadcrumb is yet in dev version and you have to code.
A solution more complete could be the follow (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;
}
}
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;
}
}