Drupal: Hierarchical taxonomical breadcrumb trail

2019-07-14 14:35发布

问题:

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!

回答1:

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.



回答2:

Taxonomy Breadcrumb seems to provide this functionality.

If you don't want to use the module, the code might provide inspiration.



回答3:

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'>&raquo;</span>", $breadcrumb) . '</div>';
        return $output;
    }
}


回答4:

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'>&raquo;</span>", $breadcrumb) . '</div>';
        return $output;
    }

}