Wordpress: Display posts by categories

Thursday, July 10th, 2008
Advertisement

Subscribe.
Enter your email:

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:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

Leave a Reply

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