Post Titles By Category

This code will list post titles, with links to the full posts, by category name.

It does not provide pagination, so the page could get quite long.  On a large site, the number of queries could cause timeouts or server overload.

It is not complete by itself as it needs to be integrated with your theme by putting in the appropriate get_header(), divs, get_sidebar(), etc.

$hide_empty = true;    // Hide category names that have no posts.
$hierarchical = true;  // Show empty category names when in a hierarchy
$posts_per_category = 5; // The max number of posts to show in a category.
$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('posts_per_page' => $posts_per_category, '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>';


Leave a Reply

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