WordPress: Display posts by categories

This function could be used to display all categories and their posts. One example of its usage is for the Archive page.

To use it copy and paste the function into the file “functions.php” located inside the “wp-content\themes\your theme” folder. You may have to create that file if it does not exist yet.

To call the function, use posts_by_cats(3), where 3 is the number of post to be displayed in each category.

<?php
/*
This funtion will display posts for each parent categories
*/
function posts_by_cats($num_of_posts) {
    global $wpdb;

    // query the cat id
    // remove `parent` = 0 to display all categories
    $sql = "SELECT `term_id` FROM $wpdb->term_taxonomy WHERE `taxonomy`='category' AND `parent` = 0 AND `count` != 0";
    $cats = $wpdb->get_results($sql, ARRAY_A);

    //display posts for each cat
    foreach ($cats as $cat) {
      $cat_id = $cat['term_id'];

      // query the cat name
      $sql = sprintf("SELECT `name` FROM $wpdb->terms WHERE `term_id`=%d", $cat_id);
      $cat_name = $wpdb->get_var($sql);

      echo '';
      echo '<h3><a href="'. get_category_link($cat_id) . '">' . $cat_name . '</a></h3>';

      // query all the posts for each cat
      query_posts(sprintf("cat=%d&amp;showposts=%d", $cat_id, $num_of_posts));

      // the loop
      if (have_posts()) :
          echo "
<ul>";
          while(have_posts()) : the_post();
  ?>
<li><a title="<?php the_title_attribute(); ?>" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
  <?php
          endwhile;
          echo '<li><a href="'. get_category_link($cat_id) . '">(more)</a></li>';
          echo "</ul>";
      endif;
      echo "

";
    }
}

?>
</li>
</ul>
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Related

This entry was posted in WordPress and tagged . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>