X

List All Categories with Posts

Snippets by IsItWP

You may want to list all categories with posts in WordPress. It’ll help your users to easily find out the post they’re looking for.

Instructions: Add the following code to the functions.php file of your WordPress theme.


<?php
//for each category, show all posts
$cat_args=array(
  'orderby' => 'name',
  'order' => 'ASC'
   );
$categories=get_categories($cat_args);
  foreach($categories as $category) {
    $args=array(
      'showposts' => -1,
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
    );
    $posts=get_posts($args);
      if ($posts) {
        echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
        foreach($posts as $post) {
          setup_postdata($post); ?>
          <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
          <?php
        } // foreach($posts
      } // if ($posts
    } // foreach($categories
?>

You may also enjoy removing default taxonomies in WordPress.

Comments   Leave a Reply

  1. Hi, this is very helpful how possible is to get the number of posts fro each parent category?

  2. this is great, but what if i need pagination?

  3. I use this code snippet but I had to add global $post variable. It duplicate some posts if global $post variable is not present.

    BTW. Thank you!

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!