treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Getting x number of posts from each category - WP

  • I'm building my first WordPress site, and The Loop is giving me a bit of a headache. I've read through the official document from WordPress, but nothing good came of it.

    What I'm looking to do is get 4 posts from each category. I have an accordion-like layout, so each "tab" will show 4 posts from their respective category. So far I can only seem to show the 10 most recent posts, which isn't any good, as I might do 5 posts in a row in one category, and so on...

    Also, if you have any good hints on how I could go about doing the splitting of posts depending on their category, that would be helpful. Right now, I'm using jQuery to pick out posts with class of "category-catName", and moving them to the correct place.


    <div id=\"wrapper\">
    <div id=\"category1\">
    <h1>Category 1 Header</h1>
    </div>
    <div id=\"category2\">
    <h1>Category 2 Header</h1>
    </div>
    ...
    </div>


    Then getting all posts, picking out posts depening on their category, and placing them in their category-div, under the header.
  • <?php $recent = new WP_Query(\"cat=3&showposts=1\"); while($recent->have_posts()) : $recent->the_post();?>
    <h2><a href=\"<?php the_permalink() ?>\" rel=\"bookmark\"><?php the_title(); ?></a></h2>
    <?php the_content(__('Read the story &raquo;'));?><div style=\"clear:both;\"></div>
    <?php endwhile; ?>


    cat=3
    Category ID number
    showposts=
    Number of posts to show

    The rest of the code is optional
  • Just saw this post. The tricky thing is in a standard query_posts call you can only specify the max. number of posts to show, not the number of posts per category. To get around this we have to make a seperate query for each category.

    The following snippet is an example:
    <?php
    $categories = get_categories(\"hierarchical=0&hide_empty=true\");
    $showposts = 4; // the number of posts per category to showposts

    echo \"<ul>\";
    foreach ($categories as $category) {
    echo \"<li class=\\"category-$category->term_id\\">\";
    echo \"<h2>$category->name</h2>\";
    echo \"<ul>\";

    $category_posts = new WP_Query(\"cat=$category->term_id&showposts=$showposts&published=true\");
    while ($category_posts->have_posts() ) {
    $category_posts->the_post();

    echo \"<li>\";
    the_title(); // output the post here using the_content, the_permalink, etc...
    echo \"</li>\";
    }

    echo \"</ul>\n\";
    }

    echo \"</ul>\";
    ?>