posted in Wordpress  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.