WordPress通过子ID获取当前文章术语的父级分类

7

我有一个术语子项的ID,在页面中,我需要通过子项ID找到它的父项,这是可能的,也许有人可以帮忙吗?

2个回答

10

这就是 get_term 函数的作用:

$term_id = 21; // Lucky number :)

$child_term = get_term( $term_id, 'category' );
$parent_term = get_term( $child_term->parent, 'category' );

'category'替换为您正在使用的任何分类法。


谢谢,请编辑的不是 $term->parent 而是 $child_term->parent - Mantas Kudeikis

3
$terms = get_the_terms( $_product->id , 'product_cat');
if($terms) {
    foreach( $terms as $term ) {
        $term = get_term_by("id", $term->parent, "product_cat");
        if ($term->parent > 0) {
            $term = get_term_by("id", $term->parent, "product_cat");
        }
        $cat_obj = get_term($term->term_id, 'product_cat');
        $cat_name = $cat_obj->name;
    }
}
echo '<br />('. $cat_name . ')';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接