最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Handling Multi-level custom taxonomy hierarchy

programmeradmin2浏览0评论

I am trying to sort through a multi level hierarchy in a custom taxonomy.

I have custom taxonomy's with multiple sub taxonomy's. Eg:

Level1
-Level2
--Level3 

ect

At the moment I can use get_term_children() to return the children for a top level taxonomy but this doesn't tell me anything about there position in the hierarchy.

I am trying to sort through a multi level hierarchy in a custom taxonomy.

I have custom taxonomy's with multiple sub taxonomy's. Eg:

Level1
-Level2
--Level3 

ect

At the moment I can use get_term_children() to return the children for a top level taxonomy but this doesn't tell me anything about there position in the hierarchy.

Share Improve this question edited Jun 14, 2020 at 8:21 JJS 1238 bronze badges asked Jan 30, 2014 at 16:41 Frank AstinFrank Astin 551 silver badge7 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

You'll probably have to run a cycle using get_terms() paired with the 'parent' attribute.

$args = array( 'parent' => 0 );
$parents = get_terms( array( 'custom-tax' ), $args );
foreach ( $parents as $parent ) {
    echo $parent->name;
    $args['parent'] = $parent->term_id;
    if ( $children = get_terms( array( 'custom-tax' ), $args ) ) {
        foreach ( $children as $child ) {
            echo $child->name;
        }
    }
}

You may be able to rewrite the "if ( $children..." into a while loop if you need more recursion than that.

You can recursively create a hierarchical structure using this function:

function sort_hierarchical(array &$cats, array &$into, $parent_id = 0){

    foreach ($cats as $i => $cat) {
        if ($cat->parent == $parent_id) {
            $into[$cat->term_id] = $cat;
            unset($cats[$i]);
        }
    }

    foreach ($into as $top_cat) {
        $top_cat->children = array();
        sort_hierarchical($cats, $top_cat->children, $top_cat->term_id);
    }
}

And use it like this:

$terms = get_terms(array('taxonomy' => 'category', 'hide_empty' => false));
$cats = array();
sort_hierarchical($terms,$cats) ;
发布评论

评论列表(0)

  1. 暂无评论