php Wordpress 通过子 ID 获取当前的 post term 父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14591491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:35:29  来源:igfitidea点击:

Wordpress get current post term parent by child ID

phpwordpressparent-childterm

提问by Mantas Kudeikis

In page I have ID of term child, I need find out this child parent by child ID, it's passible, maybe someone can help with this ?

在页面中我有术语孩子的 ID,我需要通过孩子 ID 找出这个孩子的父母,这是可行的,也许有人可以帮助解决这个问题?

回答by Joseph Silber

That's what the get_termfunction is for:

这就是该get_term功能的用途:

$term_id = 21; // Lucky number :)

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

Replace 'category'with whatever taxonomy you're using.

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

回答by dfa

$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 . ')';