<?php$categories = $wpdb->get_results("SELECT * FROM $wpdb->categories WHERE category_count > 0 ORDER BY cat_name DESC"); // query database for categories with at least one post;foreach($categories as $category) : // start loop to display category list?><li><a href="<?php echo get_category_link($category->cat_ID); ?>"><?php echo $category->cat_name; ?></a><?php if( is_single() ) : // on a single post page we need to dig up the category ID global $post; $cat = get_the_category(); $cat = $cat[0]->cat_ID; endif; if( (is_category() || is_single()) && ($category->cat_ID === $cat) ) : // current category query is same as category presently in the loop?> <ul><?php $catq = new WP_Query("cat=$cat&showposts=-1"); // query posts from current category while($catq->have_posts()) : $catq->the_post(); // start posts in category loop?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php endwhile; // end posts in category loop?> </ul><?php endif; // end current category query test ?></li><?php endforeach; // end loop to display category list ?>