March 8th, 2009 by

Recently my client’s design required displaying posts in sidebar only from one category. To solve this problem I decided to use class WP_Query.

The first we have to create instance of WP_Query:

Then call method query(); to start the query. This is actually same as you would be using query_posts();
Parameter cat indicates which category’s posts are shown. Parameter showposts is the number of posts to be displayed.

query('cat=1&showposts=5'); ?>

Now we can use loop:

<?php while($recent->have_posts()) : $recent->the_post(); ?>
<!-- Here goes some code -->
<?php endwhile; ?>

Final code that displays last 5 posts’ permalinks from category with ID=1 looks like this:

<h2>Last posts</h2>
<?php $recent = new WP_Query(); ?>
<?php $recent->query('cat=1&showposts=5'); ?>
<?php while($recent->have_posts()) : $recent->the_post(); ?>
<ul>
	<li>
            <a href="<?php the_permalink(); ?>">
            <?php the_title(); ?>
            </a>
       </li>
</ul>
<?php endwhile; ?>

Using your own WP_Query instance and loop prevents you from problems that might cause plugins’ loops and use of conditional tags.

32 Responses to “WordPress: display posts from certain category”

  1. Chad Buie says:

    Awww man this is killer…this is really powerful stuff…especially considering the use for PHP anyway is a feat in itself. But thanks for illustrating how to use the query class to and use the id of the post…appreciate it much…you should have a donation button up man..saved me hours..

  2. Chris Boggs says:

    Just a thanks man. This solution is greatly appreciated! -c-

  3. Outstanding. Thanks for the huge tip.

  4. xenomorf says:

    wow.. thank you very much sir for this tutorial. i wasted a few hours of my precious time just to figure how to display the last five post. i never thought of using WP_QUERY().

    thank you!

  5. Florian says:

    This is great code. But, on my site shows the code the posts, from the good category, but this shows it 5 times. 1 time is needed :) What can I do?

  6. This worked great for me – thanks so much. With a little CSS, DIVs and PHP – it works great.

Trackbacks/Pingbacks 1

Leave a Reply