Display as tree terms of taxonomy and custom posts for each term of taxonomy

Question

I have cpt “Document” and Taxonomy Document categories with terms “AML” and “Corporate Governance”. For each term there are children “EU”, “National Law”, etc..
I want to display as Tree All Terms, subterms and assigned posts (My tree with Terms/subterms https://i.stack.imgur.com/tC5JQ.png )
I want to add assigned posts to each term as leafs to the tree. My code is the following:

function rgt_generate_taxonomy_tree_lampros($taxonomy) {
    $taxonomies = get_terms(array(
        'taxonomy' => $taxonomy,
        'hide_empty' => false
    ));
    $grouped = array();
    foreach ( $taxonomies as $taxonomy ) {
        $par = $taxonomy->parent;
        if ( !isset($grouped[$par]) ) $grouped[$par] = array();
        array_push($grouped[$par], $taxonomy);
    }
    $tree = array();
    rgt_fill_taxonomy_tree_lampros(0, $tree, $grouped);
    
    return $tree;
}

function rgt_fill_taxonomy_tree_lampros($parent_id, &$parent, $data) {
    if ( !isset($data[$parent_id]) || count($data[$parent_id]) == 0 ) return;
    $parent['children'] = array();
    foreach ( $data[$parent_id] as $item ) {
        $newitem = array(
            'name' => $item->name,
            'id' => $item->slug
        );
        rgt_fill_taxonomy_tree_lampros($item->term_id, $newitem, $data);
        array_push( $parent['children'], $newitem );
    }
    $parent['children'] = rgt_array_sort($parent['children'], 'name');
}

0
Buttered_Toast 2 months 2021-10-11T05:06:48-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse