Hierarchical Category List with Post Titles

If your wordpress site is organized with categories, it might be very useful to have a template to show an organized list of all categories with the associated posts.
This would work similar to the category widget with the setting ‘hierarchical’ – only that for each category, all the post titles are listed with links to the individual post.

This is the code:

<?php
// http://codex.wordpress.org/Function_Reference/get_categories
 
 foreach( get_categories('hide_empty=0') as $cat ) :
 if( !$cat->parent ) {
 echo '<ul><li><strong>' . $cat->name . '</strong></li>';
 process_cat_tree( $cat->term_id );
 }
 endforeach;
 
 wp_reset_query(); //to reset all trouble done to the original query

function process_cat_tree( $cat ) {
 
 $args = array('category__in' => array( $cat ), 'numberposts' => -1);
 $cat_posts = get_posts( $args );
 
 if( $cat_posts ) :
 foreach( $cat_posts as $post ) :
 echo '<li>';
 echo '<a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a>';
 echo '</li>';
 endforeach;
 endif;
 
 $next = get_categories('hide_empty=0&parent=' . $cat);
 
 if( $next ) :
 foreach( $next as $cat ) :
 echo '<ul><li><strong>' . $cat->name . '</strong></li>';
 process_cat_tree( $cat->term_id );
 endforeach;
 endif;
 
 echo '</ul>';
}
?>

The first step is to find all top level categories (generated in alphabetical order) – which is simply done with the wordpress function ‘get_categories()’ and by checking if the category has a parent.
Caveat: because the code is checking for top level categories only, you can’t directly use the parameters of ‘get_categories()’ (see the Codex, the mostly unread documentation of WordPress) without some customization of the top section of the code.

The second step is to show the titles of all available posts for each top level category, linked to the full individual post; done with ‘get_posts()’ and ‘get_permalink()’.

The third step is to find possible direct child categories for this (top) category; done with the ‘parent’ parameter of ‘get_categories()’.

Then step 2 and 3 are repeated until all possible categories are dealt with.

Thank MICHAEL – transformationpowertools