Nested Accordions For Taxonomies [closed]

I’m trying to develop a FAQ accordion that can be nested four times. This means under the first taxonomy there comes the next, and after that another, and after that the contents appear, pretty much like the following picture;

enter image description here

I’ve tried many plugins such as: Spider FAQ, Ultimate FAQ, WP responsive FAQ with category plugin. I even tried a combination of a few, by adding the short code in the text area of another FAQ shortcode. It works up to the second level but it never makes it to the third, I’ve tried even coding it but still wasn’t successful. How can I achieve this?

Answer

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.

Attribution
Source : Link , Question Author : Neophyte Polyhistor , Answer Author : jgraup

Leave a Comment