Wordpress - 按层次结构获取帖子的分类



我想分层获取一个帖子的所有分类(循环)。示例我有这些分类法,括号中是税收的 ID。

Tax1(1)
-Tax2(3)
--Tax3(2)

我想将它们收集成一个阵列,也许是按这个顺序。现在我设法得到了这 3 个的数组,但顺序是错误的。我不能按 id 排序,因为一开始没有对 ID 进行排序。我也不能按名称和鼻涕虫订购。(我目前的分类法的名称不是Tax1,Tax2...)

我目前拥有的代码是

$args = array('orderby' => 'term_order', 'order' => 'ASC', 'fields' => 'all');
$productcategories = wp_get_object_terms($post->ID, 'guide_type', $args);

使用 "Wordpress" Walker 类创建分类的层次结构

<?php
class Walker_Quickstart extends Walker {
    // Tell Walker where to inherit it's parent and id values
    var $db_fields = array(
        'parent' => 'parent', 
        'id'     => 'term_id' 
    );
    /**
     * At the start of each element, output a <p> tag structure.
     */
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $output .= sprintf( "n<p>%s %s (%s)</p>n",
            str_repeat('&dash;', $depth),
            $item->name,
            $item->term_id            
        );
    }
}?>

此类将创建元素的层次结构。将此类与返回的元素一起使用,如下所示:

$args = array('orderby' => 'term_order', 'order' => 'ASC', 'fields' => 'all');
$productcategories = wp_get_object_terms($post->ID, 'guide_type', $args);
$walk = new Walker_Quickstart();
echo $walk->walk($productcategories, 0);

即将通过我制作的这个函数得到一些东西,但是维卡什·库马尔给了我一个更好的答案,谢谢!

function get_term_top_most_parent($post_id, $taxonomy){
    $return = array();
    $registeredcat = 0;
    $newparent = '';

    $catcount = 0;
    $firstlevels = wp_get_object_terms( $post_id, $taxonomy); //post id, taxo, args
    foreach ($firstlevels as $key => $value){
        if($value->parent == 0 ){
            //$firstlevel = $value->term_id; //23
            $newparent = $value->term_id;
            array_push($return, $value);
            $registeredcat += 1;
        }
        $catcount += 1;
    }
return $return;
}

最新更新