19 Nov, 2010
Simulate Breadcrumb Navigation with Hierarchical Custom Taxonomies
Posted by: Jennifer In: WordPress|WordPress Hacks|WordPress scripts
Code is below with comments to explain what's going on. This code would go on your taxonomy.php page…
<?php
//get current term info
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
//store curent term's id as first in the array
$breadcrumbarray[] = $term->term_id;
//transfer the term info object so we don't mess it up
$tempterm = $term;
//backward crawl terms...
//if the current term in the crawl has a parent - get it's parent's id...
while ($tempterm->parent != 0) {
$tempterm = get_term_by('id',$tempterm->parent,get_query_var( 'taxonomy' ));
// and store it in the array
$breadcrumbarray[] .= $tempterm->term_id;
}
//now reverse order the array so it goes from parent to child...
$breadcrumbarray = array_reverse($breadcrumbarray);
//now we'll loop through our array to display each item in the parent to child order and with links...
$isfirst = true;
foreach($breadcrumbarray as $termid) {
if (!$isfirst) echo " ยป ";
$isfirst = false;
// get all the info again for the current term id in the array
$terminfo = get_term_by('id',$termid,get_query_var( 'taxonomy' ));
//show links for all terms except the current one..
if ($terminfo->term_id != $term->term_id) {
//get the URL for that terms's page
$url = get_term_link( $terminfo->name, get_query_var( 'taxonomy' ) );
echo '<a href="'.$url.'">'.$terminfo->name.'</a>';
} else {
echo $terminfo->name;
}
}
?>
I couldn't see an easier (or built in) way to do this… if there is, do let me know. Seems like it's a simple thing that shouldn't require so much code…