Nested Accordions For Taxonomies [closed]

I’m sure you can find accordion code samples anywhere. It might be helpful to convert terms into a structure that is more conducive to nested elements.

<?php

// Get terms as nested array

function get_nested_terms ($taxonomy, $array=array(), $args=array() ) {

    $args = wp_parse_args($args, array(
        'orderby'    => 'count',
        'parent'     => 0,  
        'hide_empty' => true
    ));


    $terms = get_terms($taxonomy, $args);

    foreach ( $terms as $term ) {

        $args['parent'] = $term->term_id;
        $children = get_nested_terms ( $taxonomy, array(), $args);

        $array [$term->term_id] = array(
            'term'     => $term,
            'children' => $children
        );

    }
    return $array;
}

// Render HTML from nested terms array

function render_nested_terms($array, $level = 0){
    $level++;
    foreach ( $array as $term_info ) {
        $classes = array(
            "level-" . $level,
            empty($term_info['children'] ) ? 'no-children' : 'has-children'
        );
        echo '<ul class="' . implode (' ', $classes ) . '" ><li>';

        // Showing the term name, 
        // but you could include term content below this item

        echo "term: " . $term_info['term']->name;

        // Render the nested items

        if( ! empty($term_info['children'] )) {
            render_nested_terms ( $term_info['children'], $level );
        }

        echo '</li></ul>';

    }
}

First we’ll run one function to get all the terms you want to use. Set hide_empty to true to only return categories that have content associated with them.

$options = array(
    'parent'     => 0, 
    'hide_empty' => false
);

$nested_terms = get_nested_terms ('category', array(), $options );

Next, loop through the nested elements and render HTML content.

render_nested_terms ($nested_terms);

At this point you’ll want to add JavaScript or whatever based on how you architected your nested elements.