代码
function wc_origin_trail_ancestor( $link = false, $trail = false ) {
if (is_product_category()) {
global $wp_query;
$q_obj = $wp_query->get_queried_object();
$cat_id = $q_obj->term_id;
$descendant = get_term_by("id", $cat_id, "product_cat");
$descendant_id = $descendant->term_id;
$ancestors = get_ancestors($cat_id, \'product_cat\');
$ancestors = array_reverse($ancestors);
$origin_ancestor = get_term_by("id", $ancestors[0], "product_cat");
$origin_ancestor_id = $origin_ancestor->term_id;
$ac = count($ancestors);
} else if ( is_product() ) {
$ancestors = get_the_terms( $post->ID, \'product_cat\' );
$i = 0;
foreach($ancestors as $ancestor) {
if( $i == 0 ) {
$origin_ancestor = $ancestor;
$origin_ancestor_id = $origin_ancestor->term_id;
}
}
$ancestors = array_reverse($ancestors);
$ac = count($ancestors);
$descendant = $ancestors[0];
$descendant_id = $descendant->term_id;
$ancestors = array_reverse(get_ancestors($descendant_id, \'product_cat\'));
}
$c = 1;
if( $trail == false ){
$origin_ancestor_term = get_term_by("id", $origin_ancestor_id, "product_cat");
$origin_ancestor_link = get_term_link( $origin_ancestor_term->slug, $origin_ancestor_term->taxonomy );
if($link == true)
echo \'<a href="\'. $origin_ancestor_link .\'">\';
echo $origin_ancestor->name;
if($link == true)
echo \'</a>\';
}else{
foreach ($ancestors as $ancestor) {
$ancestor_term = get_term_by("id", $ancestor, "product_cat");
$ancestor_link = get_term_link( $ancestor_term->slug, $ancestor_term->taxonomy );
if($c++ == 1)
echo \'» \';
else if($c++ != 1 || $c++ != $ac)
echo \' » \';
if($link == true)
echo \'<a href="\'. $ancestor_link .\'">\';
echo $ancestor_term->name;
if($link == true)
echo \'</a>\';
}
$descendant_term = get_term_by("id", $descendant_id, "product_cat");
$descendant_link = get_term_link( $descendant_term->slug, $descendant_term->taxonomy );
echo \' » \';
if($link == true)
echo \'<a href="\'. $descendant_link .\'">\';
echo $descendant->name;
if($link == true)
echo \'</a>\';
}
}
如何使用顶级,起源祖先;无链接
wc_origin_trail_ancestor();
只是顶层,起源祖先;带链接
wc_origin_trail_ancestor(true);
祖先足迹;无链接
wc_origin_trail_ancestor(false,true);
祖先足迹;带链接
wc_origin_trail_ancestor(true,true);
如果一个产品有多个主要/顶级类别,或者至少不会全部显示,那么li>
注释将不起作用对于同一级别上的多个子类别,情况应相同我没有对上述几点做进一步的测试,因为该函数满足了我对该项目的所有要求