A common need when developing for WordPress is to display posts for a certain category.

This can come in very handy when you only want to show certain posts on a certain page template, or if you want to display the latest posts from a certain category in your footer. There are plenty of other use cases…

To do this we’ll create a ul with the query_posts() function inside, and then loop through our lis with anchor tags wrapping the post title. This will essentially create a clickable list of posts.

<ul class="posts">
	<?php query_posts('cat=5'); while (have_posts()) : the_post(); ?>
		<li><a href='<?php the_permalink() ?>'><?php the_title(); ?></a></li>
	<?php endwhile; ?>
	
	<?php wp_reset_query(); ?>
</ul>

In this example I’m querying (displaying) posts with category ID of 5. If you’re not familiar with using IDs I suggest installing the “Reveal IDs” WordPress plugin. It’s super helpful.

NOTE: You’ll also notice that I have the wp_reset_query() function after my query. This is needed so WordPress can “restore” things back to normal (super technical stuff…).

Other Options

You can also pass other options to make your query more refined. For example, you may want to limit the amount of posts that display and/or display posts based on specific tags (examples below).

Limit Number of Posts

<ul class="posts">
	<?php query_posts('cat=5&showposts=10'); while (have_posts()) : the_post(); ?>
		<li><a href='<?php the_permalink() ?>'><?php the_title(); ?></a></li>
	<?php endwhile; ?>
	
	<?php wp_reset_query(); ?>
</ul>

Display Posts based on Tags

<ul class="posts">
	<?php query_posts('cat=5&showposts=10&tag=demo'); while (have_posts()) : the_post(); ?>
		<li><a href='<?php the_permalink() ?>'><?php the_title(); ?></a></li>
	<?php endwhile; ?>
	
	<?php wp_reset_query(); ?>
</ul>

Conclusion

As you can see it’s pretty simple to display posts from a specific category, and it’s super flexible. For the complete reference visit the WordPress Codex page for query_posts(). I hope this was helpful!

Discussion

4 thoughts on “How to display WordPress Posts for a specific Category”
Leave a Comment

Your email address will not be published. Required fields are marked *


Ali Jafarian

Tutorial Category WordPress
Comments 4 comments

Did you find value here?

If yes, please jump on my email list for more free stuff. I'll keep bringing the heat.

Get on the List