代码之家  ›  专栏  ›  技术社区  ›  Antoine Dionne

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

  •  1
  • Antoine Dionne  · 技术社区  · 9 年前

    我想得到一篇文章的所有分类法(循环),层次化。示例我有这些分类法,括号中有税号。

    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);
    
    2 回复  |  直到 9 年前
        1
  •  3
  •   Vikash Kumar    9 年前

    使用“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);
    
        2
  •  0
  •   Antoine Dionne    9 年前

    本打算用我做的这个功能得到一些东西,但维卡什·库马尔给了我一个更好的答案,谢谢!

    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;
    }