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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?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-&gt;terms WHERE `term_id`=%d", $cat_id);
      $cat_name = $wpdb-&gt;get_var($sql);
 
      echo '<p>';
      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();
  ?&gt;
              <li><a title="&lt;?php the_title_attribute(); ?&gt;" href="&lt;?php the_permalink() ?&gt;" rel="bookmark"><?php the_title(); ?></a>
  <?php  
          endwhile;
          echo '<li><a href="'. get_category_link($cat_id) . '">(more)</a></li>';
          echo "</ul>";
      endif;
      echo "</p>";
    }
}
 
?>
</li></ul>

Spread/Promote this post.

Digg | Del.icio.us | Stumble | Fave It! | Reddit | Email This Post | Print Post

If you liked this post, these other posts might also be interesting to you:

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*