List Links to Posts by Category

The code below will list links to posts grouped by the category of the post.  It was developed for WP 2.9’s  default theme.

See the Codex for the Function get_terms() for documentation of the arguments that can be used to alter the terms selected.

 * @package WordPress
 * @subpackage Default_Theme
Template Name: listpostsbycategory
<?php /*
 Author: Mac McDonald
 Contact at using the Contact Me form.

 This program creates a list of posts by category as links to the posts.


<?php get_header(); ?>
<div id="content" role="main">

$hide_empty = true;
$hierarchical = true;
$args = array(
 'hide_empty' => $hide_empty,
 'hierarchical' => $hierarchical,
$catarray = get_terms('category',$args);
foreach ($catarray as $category) {
   $catid = $category->term_id;
   $link = get_category_link($catid);
   if (!$hide_empty || $hierarchical) {
      echo "<h2><a href='$link' title='Link to Category $category->name' >Posts for Category $category->name</a></h2>";
   //echo '<p>';print_r($category);echo '</p>';
   $myquery = new WP_Query(array('category__in' => array($catid)));
   if ($myquery->have_posts()) :
      if ($hide_empty && !$hierarchical ) echo "<h2><a href='$link' title='Link to Category $category->name' >Posts for Category $category->name</a></h2>";
      while ($myquery->have_posts()) : $myquery->the_post(); ?>
         <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
      <?php endwhile;
      if (!$hide_empty || $hierarchical) echo '<p> &nbsp;&nbsp;&nbsp;- None Found -</p>';

</div><!-- End content -->
<?php get_footer(); ?>

2 Responses to List Links to Posts by Category

  • Mac says:

    This code is a sample Template. Copy it to your theme’s folder with a name like ‘listbycategory.php’. Create a new Page (not Post) and assign it as the Template. It is written for the WP Default theme, so you will need to modify it for your theme.

  • Flora says:

    Where do you post this code?

Leave a Reply

Your email address will not be published. Required fields are marked *