Back WordPress

How to List Categories along with Their Posts

WRITTEN BY ON 17 Mar 2011
14,255 VIEWS • SHARES
4 comments

To help site visitor finding one or two categories, We can use default widget or wp_list_categories to list the categories. In some case, We want to display the categories along with their posts. Unfortunately, this default widget and function can’t perform that. But this snippet can. Read more : http://www.dynamicwp.net/articles-and-tutorials/how-to-list-categories-along-with-their-posts/

PHP

Put the code in sidebar, page template or wherever You want to display the categories

<?php
//get all categories then display all posts in each term
$taxonomy = 'category';
$param_type = 'category__in';
$term_args=array(
  'orderby' => 'name',
  'order' => 'ASC'
);
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
  foreach( $terms as $term ) {
    $args=array(
      "$param_type" => array($term->term_id),
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {  ?>
      <div class="category section">
	    <h3><?php echo 'Category '.$term->name;?></h3>
	    <ul>
	    <?php
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
       <?php
      endwhile;
      ?>
      </ul>
      </div>
 <?php
    }
  }
}
wp_reset_query();  // Restore global post data stomped by the_post().
?>

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

4 comments
squizeers 12 years ago
Is there any way to apply active state to the post title in the above code?For example:

Category1
cat1post1
cat1post2
<u>cat1post3</u>
cat1post4
cat1post5
Category2
cat2post1
cat2post2
cat2post3
cat2post4
cat2post5

If i am viewing "cat1post3", I want to give it an active state.










Reply
Taylor McCaslin 12 years ago
I've been searching the internet for this solution, after days of failed attempts, I stumbled upon this, works perfectly! THANK YOU!
Reply
Allen 12 years ago
Hello, thanks for posting this code.

Instead of displaying the list of posts in all categories. If it doesn't take too much trouble, using that code above. Could you modify it so it only displays the list of posts in one chosen category.

Thanks.
Reply
Allen 12 years ago
Please ignore that last comment about modifying your php code. I have just figured out how to display the list of posts in one category.
Reply