Generating nested category lists in WordPress templates using get_terms

I wanted to create an index style page of site links organised by child category nested below each parent category.

The desired layout suggests a nested loop so first we need to list our parent categories:

Note the commented line where
'parent' => 0
ensures that only the top level category is selected.

If this is pasted into a page template then you should now see a list of your parent categories.

Now a look at the loop that will go inside this one:

Now put it all together:

 

Just a couple of caveats with this.

When assigning a category to a post you must check the sub category and the associated parent category or they won’t be displayed.

This snippet only works with one level of subcategory.

2 thoughts on “Generating nested category lists in WordPress templates using get_terms

  1. oh… I’m so close. In my code it loops and displays everything several times. main category -> sub-category -> link to detail page.

    need to get it to only loop once and next to start with the list ‘closed’ and able to toggle expand and collapse on main category and subcategory to reveal link to business.

    code I am using is : 0 ) ;
    $parentcategories = get_terms ( “bowencategory”, $cat_args ) ;
    $no_of_categories = count ( $parentcategories ) ;

    if ( $no_of_categories > 0 ) {

    foreach ( $parentcategories as $parentcategory ) {

    echo ” . $parentcategory ->name . ” ;

    $parent_id = $parentcategory ->term_id;
    $subcategories = get_terms ( ‘bowencategory’, array ( ‘child_of’ => $parent_id, ‘hide_empty’ => false ) ) ;

    foreach ( $subcategories as $subcategory ) {

    $args = array (
    ‘post-type’=> ‘bowenbusiness2’,
    ‘orderby’=> ‘businessname’,
    ‘order’=> ‘ASC’,
    ‘post_per_page’=> -1,
    ‘nopaging’=> ‘true’,
    ‘bowencategory’=> $subcategory->name
    );

    echo ” . $subcategory->name . ”;

    query_posts ( $args ) ;

    while ( have_posts () ) : the_post () ;

    ?>
    <a href="”>
    <?php

    endwhile;

    wp_reset_query () ;

    echo '’ ;

    }

    echo ” ;

    }
    }

    ?>

    This is in a Pod Template.

    results in : http://www.bowen-island-bc.ca/testlist2/

    any tips? really near to what I want to achieve so thanks for your code so far.

    regards

    Hugh

    1. Hello Hugh,

      In your example above you’re missing the ul li... mark up which opens and closes each parent category list as you require.

      As far as I’m aware in my example these are nested correctly (maybe this needs checking).

      EDIT: just realised my comments handle code really badly (ie not at all!) so your code might have got messed up when you pasted it. Must get this sorted soon!

Leave a Reply