Show Posts by Category in WordPress

One of the most important part of creating a custom WordPress template is to know how to retrieve a certain category to be displayed on a page.

This is usually seen on home pages where there is an organized list or updates such as news, latest gadgets, etc.

The code below will help you how to retrieve a particular post based on a category in WordPress. It will also tell you how many posts will display on the page by category.

<?php ( query_posts('category_name=news&showposts=3') ) ; ?>
		<h2 class="newstitle">Updates</h2>
			<ul class="newslist">
			<?php while ( have_posts() ) : the_post(); ?>
				<li><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></li>
			<?php endwhile; ?>
			</ul>
<?php wp_reset_query(); ?>

The codes above will display the latest 3 posts under the category news. You can replace category and the number of post to be shown.  There are other parameters that can be used in retrieving a post based on categories.

Some Common Category Parameters

  • cat
  • category_name
  • tag
  • posts_per_page
  • order
  • orderby

More Complex Example

<?php if ( query_posts('category_name=news,staff,blog&showposts=10&orderby=comment_count&tag=home') ) : ?>	

			<?php while ( have_posts() ) : the_post(); ?>
				<p><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></p>
			<?php endwhile; ?>

<?php wp_reset_query(); ?>
*Some links may contain affiliate links. I may get small commission from your purchases to fund this website and to avoid annoying ads.