简体   繁体   English

如何获取当前职位类型的唯一子条款?

[英]How to get only child terms of current post type?

Having a custom post type 'pubs' with custom taxonomy 'types' in which admin enter parent terms and their child terms. 有一个具有自定义分类法“类型”的自定义帖子类型“ pubs”,管理员可以在其中输入父项及其子项。 Using this code to get all the terms of current post type: 使用此代码获取当前帖子类型的所有条款:

$object_terms = wp_get_object_terms($post->ID, 'types', array('fields' => 'all'));
    if ($object_terms) {
        echo '' . '' . '' ;
        $res = '';
        foreach ($object_terms as $term) {
            $res .=  $term->name . ',';
        }
        echo rtrim($res,' ,').'' . '';
    }

this code displays both parent & child terms. 此代码同时显示父项和子项。 Is there any way to exclude parent terms from the result? 有什么方法可以从结果中排除父项? I need the code to display only child terms related to the current post. 我需要代码仅显示与当前帖子相关的子条款。

未经测试,但我认为,如果将以下内容放在顶部的foreach循环中,则只会得到孩子:

if ($term->parent == 0) continue;

Just for someone still looking: 仅针对仍在寻找的人:

Solution is for when you have multiple level of hierarchy and you want just last level. 解决方案是针对具有多个层次结构的层次结构,而您只需要最后一个层次结构的情况。

$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
foreach ($term_array as $term_id){
    $children=get_term_children($term_id, $taxonomy);
    if(empty($children)){
        $exclude=$term_id;
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM