Skip to content

Instantly share code, notes, and snippets.

@guizmo
Created June 30, 2012 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guizmo/3023047 to your computer and use it in GitHub Desktop.
Save guizmo/3023047 to your computer and use it in GitHub Desktop.
Print category tree
foreach( get_categories('hide_empty=1') 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>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment