感谢@ialocin在上面的评论,我接受了他的recommendation 并根据我的需要进行了调整。如果您了解WordPress是如何从上到下遍历分类层次结构的,那么从下到上遍历分类层次结构实际上相对简单。
function origin_trail_ancestor($cat_id = 0, $link = false, $trail = false) {
global $wp_query;
$anchor = "<a href=\\"%s\\">%s</a>";
$html = \'\';
$descendant = get_term_by(\'id\', $cat_id, \'taxonomy\');
$descendant_id = $descendant->term_id;
$ancestors = get_ancestors($cat_id, \'taxonomy\');
$ancestors = array_reverse($ancestors);
$origin_ancestor = get_term_by(\'id\', $ancestors[0], \'taxonomy\');
$origin_ancestor_id = $origin_ancestor->term_id;
$ac = count($ancestors);
$c = 1;
if ($trail == false) {
$origin_ancestor_term = get_term_by(\'id\', $origin_ancestor_id, \'taxonomy\');
$origin_ancestor_link = get_term_link($origin_ancestor_term->slug, $origin_ancestor_term->taxonomy);
if ($link == true) {
$html .= sprintf($anchor, $origin_ancestor_link, $origin_ancestor->name);
}
}
else {
foreach ($ancestors as $ancestor) {
$ancestor_term = get_term_by(\'id\', $ancestor, \'taxonomy\');
$ancestor_link = get_term_link($ancestor_term->slug, $ancestor_term->taxonomy);
if ($c++ == 1) {
$html .= \'\';
}
else if ($c++ != 1 || $c++ != $ac) {
$html .= \' / \';
}
if ($link == true) {
$html .= sprintf($anchor, $ancestor_link, $ancestor_term->name);
}
}
$descendant_term = get_term_by(\'id\', $descendant_id, \'taxonomy\');
$descendant_link = get_term_link( $descendant_term->slug, $descendant_term->taxonomy );
$html .= \' / \';
$anchor = "<strong>%s</strong>";
if ($link == true) {
$html .= sprintf($anchor, $descendant_term->name);
}
}
return $html;
}
然后可用于执行以下操作:
$breadcrumb = sprintf(\'<strong>You are here:</strong> %s / %s\', \'<a href="\' . site_url(\'/suppliers/\') . \'">All Suppliers</a>\', origin_trail_ancestor($main_listing_id, true, true));
在哪里
$main_listing_id
是用户正在浏览并希望从中遍历回来的当前分类id的id。
谢谢你,巴德。