Wordpress: display posts from certain category
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.

Thanks a lot… I was looking for this very simple solution for 3 hours… Thanks again.
btw do you know how I can stop showing posts from certain category? Because I only need them for my menu
@MacTeP
You can stop showing posts from certain category by adding minus before value of the category.
This will stop showing posts from category with ID 1:
< ?php $recent->query(‘cat=-1?); ?>
thank you so much, this was an incredible help after breaking my loop 324234 times with hacks
[...] you’d like to display related posts from a curtain category read this tutorial [...]
Last posts
<a href="”>
Is there a way to have the picture in post show up also ?
thanks for this – such a simple solution – and yet took me ages to find it on the net. i tip my hat to thee fine fello
Brilliant mate! You’ve been a great help, thank you!
Hey
Great code, works like a charm. Super!
I was wondering though, is there a way to get current-cat on the li’s?
Thanks!
You can check how to adjust category items here http://codex.wordpress.org/Template_Tags/wp_list_categories
Thats was good. I was really messed up. Thank you
Cheers for the code snippet. Helped me out on my latest project.
Amazing stuff Tom!! Thank you for sharing this.
Just as matter of interest, I was wondering if there is a way to parse through the style of a certain post when fetching the content with your solution.
Thanks this is what I needed. Trying to show some related posts on my sidebar..
right now i am displaying posts like. when user click on any post it is showing on top and remaining 4 posts displaying below. and when i click on downside post it supposed to come on top and rest of posts needs to follow downside.