Skip to content

Instantly share code, notes, and snippets.

@chasereeves
Created April 4, 2012 00:32
Show Gist options
  • Select an option

  • Save chasereeves/2296683 to your computer and use it in GitHub Desktop.

Select an option

Save chasereeves/2296683 to your computer and use it in GitHub Desktop.
Wordpress list all posts by categories
<?php
foreach( get_categories('hide_empty=1','order_by=name') as $cat ) :
if( !$cat->parent ) {
echo '<h2><a href="#">' . $cat->name . '</a></h2>';
echo '<ul>';
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, 'orderby' => title, 'order' => ASC);
$cat_posts = get_posts( $args );
global $post;
$IDOutsideLoop = $post->ID;
if( $cat_posts ) :
foreach( $cat_posts as $post ) : ?>
<li <?php if(is_single() && $IDOutsideLoop == $post->ID) print 'class="current-item"'; ?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php 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