WordPress Custom Taxonomy Tree view

Result:

- taxonomy 1
- taxonomy 2
- - sub-taxonomy 2-1
- - sub-taxonomy 2-2
- taxonomy 3

<?php
function custom_taxonomy_tree_walker( $taxonomy, $parent = 0 ) {
    $terms = get_terms( $taxonomy, array( 'parent' => $parent, 'hide_empty' => false ) );
    if( count($terms) > 0 ) {
        $output = '<ul>';
        foreach ($terms as $term) {
            // function calls itself to display child elements, if any
            $output .= '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a>' . custom_taxonomy_tree_walker($taxonomy, $term->term_id) . '</li>';
        }
        $output .= '</ul>';    
        return $output;
    }
    return false;
}
 
// usage
echo custom_taxonomy_tree_walker( 'custom_taxonomy_category' );
?>

Leave a Reply

Your email address will not be published. Required fields are marked *