仅从wp_GET_POST_TERMS获取父术语

时间:2013-03-23 作者:javy

我有一个自定义的帖子类型,它设置了层次分类法。例如,我的帖子类型“project”的类别为

 A
   A.1
 B
 C
我正在尝试将分类显示为上的类<li> 每个帖子的项目,但我只想显示顶级家长。对于我正在查看的帖子,它被分类为A.1和C,但我想返回A和C。

我正在使用\'parent\' => 0 然而,在args中,它给了我A.1和C。我也尝试使用\'hide_empty\' => 0 但这似乎没有帮助。

这是我的代码:

 function project_get_item_classes($post_id = null) {
     if ($post_id === null)
         return;
     $_terms = wp_get_post_terms($post_id, \'construction_type\', array( \'parent\' => 0, \'hide_empty\' => 0 ));
     foreach ($_terms as $_term) {
         echo " " . $_term->slug;
     }
 }

3 个回复
最合适的回答,由SO网友:javy 整理而成

感谢@Bainternet的帮助(这里,还有他的投入,这导致了answer in this question), 我能够拼凑出代码。

// determine the topmost parent of a term
function get_term_top_most_parent($term_id, $taxonomy){
    // start from the current term
    $parent  = get_term_by( \'id\', $term_id, $taxonomy);
    // climb up the hierarchy until we reach a term with parent = \'0\'
    while ($parent->parent != \'0\'){
        $term_id = $parent->parent;

        $parent  = get_term_by( \'id\', $term_id, $taxonomy);
    }
    return $parent;
}

// so once you have this function you can just loop over the results returned by wp_get_object_terms

function project_get_item_classes($taxonomy, $results = 1) {
    // get terms for current post
    $terms = wp_get_object_terms( get_the_ID(), \'work_type\' );
    // set vars
    $top_parent_terms = array();
    foreach ( $terms as $term ) {
        //get top level parent
        $top_parent = get_term_top_most_parent( $term->term_id, \'work_type\' );
        //check if you have it in your array to only add it once
        if ( !in_array( $top_parent, $top_parent_terms ) ) {
            $top_parent_terms[] = $top_parent;
        }
    }
    // build output (the HTML is up to you)

    foreach ( $top_parent_terms as $term ) {
        echo " " . $term->slug;
    }
}

SO网友:Bainternet

wp_get_post_terms 不接受\'parent\'\'hide_empty\' 仅限其参数数组中的参数\'orderby\',\'order\'\'fields\' 但您的思路是正确的,只需在回显slug之前添加一个条件检查:

function project_get_item_classes($post_id = null) {
     if ($post_id === null)
         return;
     $_terms = wp_get_post_terms($post_id, \'construction_type\');
     foreach ($_terms as $_term) {
        if ($_term->parent == 0) //check for parent terms only
            echo " " . $_term->slug;
     }
 }

SO网友:Jérome Obbiet

只需按父级排序。。。

$terms = wp_get_post_terms(  $ID , $tax, array( \'orderby\' => \'parent\', \'order\' => \'ASC\' ) );

$myparent = $terms[0];

结束

相关推荐