Ali Jafarian

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!


  • Mike

    How about based on Author?

  • How would I show posts from a specific sub-category where I only know the parent ID = 1?

    • Salemoussa

      sub-categories got a specific ID’s too, like parent categories. So search for the sub category ID and put it instead