Display post taxonomies tree

时间:2013-08-19 作者:Toni Michel Caubet

我能够为一篇文章获取自定义分类法的所有项目,如下所示:

$args=array(\'orderby\'=>\'parent\',"fields" => "all");
$term_list = wp_get_post_terms($post->ID, \'tvr_amenity\', $args);
我的问题是我想展示这棵树(尊重父母)

因此,我想按姓名和家长订购,但我在codex上找不到任何相关内容。。

知道怎么做吗?

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

What about:

$taxName = "tvr_amenity";
$terms = get_terms($taxName,array(\'parent\' => 0));
foreach($terms as $term) {
   echo \'<a href="\'.get_term_link($term->slug,$taxName).\'">\'.$term->name.\'</a>\';
   $term_children = get_term_children($term->term_id,$taxName);
   echo \'<ul>\';
   foreach($term_children as $term_child_id) {
       $term_child = get_term_by(\'id\',$term_child_id,$taxName);
       echo \'<li><a href="\' . get_term_link( $term_child->name, $taxName ) . \'">\' . $term_child->name . \'</a></li>\';
   }
   echo \'</ul>\';
}
SO网友:Dezső

所有深度都使用递归。

function tree() {

    $taxName = "custom_tax_name";
    $terms = get_terms($taxName, array(\'parent\' => 0, \'fields\' => \'ids\'));
    subtree($terms, 0, $taxName);
}

function subtree($children_ids, $parrent_id, $taxName) {

    if ( !empty($children_ids) ){
        echo \'<ul>\';
            foreach($children_ids as $term_child_id) {
                $term_child = get_term_by(\'id\', $term_child_id, $taxName);
                if ( $term_child->parent == $parrent_id) {
                    echo \'<li><a href="\' . get_term_link( $term_child->term_id, $taxName ) . \'">\' . $term_child->name . \'</a>\';
                    $term_children = get_term_children($term_child_id, $taxName);
                    subtree($term_children, $term_child_id, $taxName);
                    echo \'</li>\';
                }
            }
        echo \'</ul>\';
    }

}

结束

相关推荐

GET_TERMS不返回任何自定义分类

我有一个自定义的帖子类型,叫做project 调用自定义分类法tagportfolio我使用此代码生成以下两个: add_action(\'init\', \'project_custom_init\'); /*-- Custom Post Init Begin --*/ function project_custom_init() { $labels = array( \'name\' => _x(\'Project