WP funzione per elencare i termini di una tassonomia con la gerarchia

Questa funzione prende il termine di una tassonomia stampa una lista annidata con tutti i termini figli e viceversa.

function get_taxonomies_terms_list($taxonomy){
    $termine = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
    
    $ancestor = get_ancestors( $termine->term_id, $taxonomy );
    $childs = get_term_children( $termine->term_id, $taxonomy );
    
    array_push($childs, $termine->term_id);
    $ancestor_ids = implode(',', $ancestor);
    $child_ids = implode( ',' , $childs );
    
    if(isset($taxonomy)){
        
    $args = array (
        'taxonomy' => $taxonomy,
        'hide_empty' => 1,
        'include' => $child_ids.','.$ancestor_ids,
        'orderby' => 'name'
    );
    
    $terms = wp_list_categories( $args );
        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
            foreach ( $terms as $term ) {
                if (0 == $term->parent) { $parentsItems[] = $term; }
                if ($term->parent) { $childItems[] = $term; }
            } 
            if(is_taxonomy_hierarchical( $taxonomy )){
                foreach ($parentsItems as $parentsItem){
                    echo '<h4>'.$parentsItem->name.'</h4>';
                    echo '<ul>';
                    foreach($childItems as $childItem){
                        if ($childItem->parent == $parentsItem->term_id){
                            echo '<li>'.$childItem->name.'</li>';
                        }
                    }
                    echo '</ul>';
                }
            }else{
                echo '<ul>';
                foreach($parentsItems as $parentsItem){
                    echo '<li>'.$parentsItem->name.'</li>';
                }
                echo '</ul>';
            }
        }
    }
}

Rispondi