List WordPress Posts by Category

I saw on twitter that John Gardner was looking for a way to loop through his WordPress categories and then display all posts that belonged to that category below it. ย I thought it was a great question / problem to solve so I did a quick tutorial on how to do so.

Make sure to view video in HD ๐Ÿ™‚

First thing you need to do is setup a new page with a custom page template. It can be as simple as below but may vary depending on your theme structure. I’m using the default WordPress 2010 theme.

/* template name: Posts by Category! */
get_header(); ?>
		<div id="container">
			<div id="content" role="main">
			</div><!-- #content -->
		</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>

Then We need to get all of our categories into a variable called $cats. Once they are setup, we’ll just loop through the categories, setup a new WordPress loop for each of them, and echo out the information needed.

Here is the final code, I’ve commended each line as needed.

/* template name: Posts by Category! */
get_header(); ?>

		<div id="container">
			<div id="content" role="main">

			// get all the categories from the database
			$cats = get_categories(); 

				// loop through the categries
				foreach ($cats as $cat) {
					// setup the cateogory ID
					$cat_id= $cat->term_id;
					// Make a header for the cateogry
					echo "<h2>".$cat->name."</h2>";
					// create a custom wordpress query
					// start the wordpress loop!
					if (have_posts()) : while (have_posts()) : the_post(); ?>

						<?php // create our link now that the post is setup ?>
						<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
						<?php echo '<hr/>'; ?>

					<?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
				<?php } // done the foreach statement ?>

			</div><!-- #content -->
		</div><!-- #container -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Thats it! You can obviously customize this to your own likings. I suggest you check out and read The Loop and query_posts().

Please leave any questions or commend below!

This entry was posted in PHP, WordPress and tagged , , , . Bookmark the permalink.

104 Responses to List WordPress Posts by Category

  1. John Gardner says:

    Wes, you are the man. I was so close and had no idea. On line 19 of your code, you note cat_id in the query and my code had term_id. Once I changed that bit, everything worked like a charm. Thanks for your help!

  2. John Gardner says:

    I think I spoke too soon re: success. If you get a moment, I’d appreciate your help on this. The loop I’m running is supposed to loop through every ‘team’ (custom taxonomy) and under each team, spit out each ‘staff’ (custom post type) member. My current code spits out the tax correct, but then spits out every staff member, regardless as to whether they’re a member of the ‘team’ or not. Thoughts?

    • John Gardner says:

      So I answered my own question with a little more digging around. In the query_posts section, I used the tax I had set up (team) and then grabbed the team name and grouped that way. ‘team’ => $cat->name.

      • Eric Rasch says:

        I’m still struggling with this. I used the code from you and Wes (THANK YOU, BTW!!!), but I’m getting the same results you did, John. All my Custom Post Types are being listed under each Category (Tax).

        You said you fixed it by adding the code [code]โ€˜teamโ€™ => $cat->name[/code], but where did you add this? Did you add it or did you replace another line of code? I’m going by your code from Pastebin.

        • wesbos says:

          Pretty sure he added it in for his custom post type args. He wanted to filter out the “team” tax for the current name so he only queried for that.

          • Eric Rasch says:

            Yep, I did that, too. I just can’t get it to stop showing all posts on all categories. I’ve actually tried a bunch of different solutions, but they all lead me back to right where I’m at (displaying all posts). I’ll keep studying the code.

  3. Pingback: WordPress Community Links: Akismet the dog edition | WPCandy

  4. Pingback: WordPress Community Links: Akismet the dog edition | Technology Story

  5. Ted Avery says:

    Just throwing in another thank you, exactly the snippet of code I needed!

  6. Ryan says:

    Hi Wes thanks for posting this, it works great for categories but I’m trying to adapt it to work with custom taxonomies.

    On my posts I have additional taxonomies; topics and locations. I can get it to list the taxonomies (terms?) but it won’t list the posts. Is there any chance you could post an adapted example for taxonomies? I could post up what I’ve done but it probably wouldn’t be much use ๐Ÿ™‚

  7. This helped me in a huge way!

    in case anyone is wondering the changes he made:

    $cpt_query_args = array(
    ‘post_type’ => ‘staff’,
    ‘cat’ => $cat->cat_id,
    ‘team’ => $cat->name

  8. mahmoud samo says:

    thaaaank u man v much
    exactly the snippet of code I needed

  9. Eric Pitcock says:

    This is great. It’s really nice to have the video in addition to the code. Thank you!

  10. Michael says:

    I’m trying to figure out how you would modify this to list parent categories first, and child categories within that each parent. Any suggestions?

    • wesbos says:

      An easy way would be to add another step to the loop. So first Query the top level categories (depth=1) and then when you loop through each of the categories, query their children (child_of=$your_current_cat_variable), and then within that query the posts that belong to it.

  11. Vincent says:

    Hey, thanks for the snippet of code!

    I’m trying to show the category name in the loop as below:

    ID; ?>

    <li class="”>
    <a href="”>cat_name;?>

    but I got the same several times.

    Any idea on how I should do so they don’t duplicates?

    Grateful if I can get any help ๐Ÿ™‚

  12. thanks to many , i like your code and use , this is very use ful code for me ,
    thanks to once again many many

  13. Great tutorial! Can you help me with one last step? My client wants to list all posts in a category, which is covered here.

    Here is the additional functionality needed….

    The client wants to list the categories above the listed out categories, and have anchor references in place to bring the user down to the respective category and listed posts….

    How would you do this to make it automated where my client doesn’t have to code when she adds a category?


  14. Is it possible to do this for a custom post type and taxonomies for that post type? I’ve been trying for hours now to find an answer!!

    • wesbos says:

      Yep, instead of get_categories() you would use get_terms() and then when you query_posts() pass in post_type= and instead of cat=$cat_id you substitute in =$tax_id

  15. 0001 says:

    thanx for the briliant elegant and simple wel documented tutorial.. se implemented under all agency’s menu
    thanx again:)

  16. 0001 says:

    sorry mis type before here is the url :

    and thanx a bunch one more time…

  17. kAlAi says:

    I feel this is Nice Tutorial. I wish to display content with “Continue reading” link. So i wrote the following code

    Just it display entire content.
    How can i Add “Continue read” link when the content is too large?


  18. SlaviO says:

    Good code, but I need to use it in the sidebar, but post list also displayed on the main page content (instead of content)!!! How would fixed it?

  19. Stephanie F says:

    Finding this post probably saved my job. ๐Ÿ™‚ Thanks so much!

  20. mersin says:

    How to exclude a categody id ??

  21. Allen says:

    Thank God! Your a life Saver!

  22. mortal says:

    thanks for this! it’s a nice way to display posts. i included the thumbnails of the posts and it works like a charm.

    is there any way to exclude certain categories from the loop?

    thanks again

    • mortal says:

      there’s a strange bug for me when using your script. it always display a maximum number of 6 posts for each category. if have 10+ posts in a certain category, it only lists the 6 most recent posts. i have not changed anything. what could be the problem?

  23. sunny says:

    Thanks for quick example…

  24. minju says:

    what can I do to just select one category and show only the posts of that specific category?

  25. minju says:

    nevermind I got it

  26. gayan says:

    great job … thx

  27. LAO Sopheak says:

    WOW! it’s work great for me!!! Bravo!

    Thanks Author!

  28. who have problem with some post show and load more memory. add wp_reset_query (); before the last closing php ?>

  29. caleb says:

    hey wes,

    thanks for sharing this, it’s almost exactly what I was looking for. however, I was hoping if you could help me with something as I’m not familiar with php/wordpress.

    how can i make the category heading a link as well?


  30. Matt says:

    Can you show how to set this up with a custom post type?

  31. Matt says:

    Hey Wes,

    I modified your code above to display custom post types by category here:

  32. franck says:

    what if you have posts that are in different categories? You would end up with repeated posts.

  33. zulfiqar says:

    Great Work…..!!

  34. sasha says:

    Im rel. new to wp and running into this problem.
    Using wp clear 3.0 theme.

    All posts on main page are published in each individual cat as well.
    I have set up the cats, assigned posts to them as well, yet,
    all posts keep appearing in the cats. What can I do? This theme does not have
    category.php file.

    Any ideas would be appreciated.


  35. Dude! Thank you so much. You saved me a lot of time since I’m not a php guy and I’ve only worked with wordpress as an admin. I had to customize a theme and thought I had to read an entire book to know how wordpress works.
    Greetings from Bucaramanga – Colombia

  36. Pingback: Wordpress category loop, how to hide cats with no posts? - feed99

  37. Syed says:

    Is it possible to have different category boxes to display posts on the static front page? how do we do that ?
    I want to have a home page which will show few light weight boxes for the categories i want to display, say about 5 and posts of that respective categories show up the date & title and link to that post in new window.

    Pls pardon my ignore, i am pretty new to wordpress and php.


  38. bedh says:

    Thanks for the good example.. ๐Ÿ™‚

  39. Luke Smith says:

    For those of you who are wondering how to exclude a category from the loop:

    $cats = get_categories(“exclude=1”);

    This worked for me when I wanted to exclude the “Uncategorized” category from my loop.

  40. jan says:

    It is a nice addon to a site. Thanks for sharing the code.
    I don’t know any php coding and would like to have some white maring in front of each line. Did experiment but cannot find the code. could you please help me out?


  41. MajVoj says:

    Great job, wesbos.

    Can anyone can help me out with making the category title a link to appropriate category?

  42. MajVoj says:

    Hi guys,

    Can anyone help me out with that to make the category names a anchor. I mean, they are already anchors but they don`t link to appropriate category link.

    I don`t have any experience with PHP, but I try from my HTML knowledge to input href=” on a anchor, but without success.


  43. Rhett says:

    If your having the issue where it shows all posts, change post_per_page=100 to showposts=1

    showposts is deprecated but seemed to fix it for me, maybe post_per_page is implying pagination? Perhaps numberposts might be something to look into?

    Anyways, thanks for the code!

  44. Efrem says:

    Excellent script here.

    I’m having the same problem as an earlier poster–only the first 10 Posts are showing up in Categories where I know there are 17+ posts.

    Any idea on how to correct this would be immensely appreciated.


  45. Ricardo C.S says:

    im using wptouch on my website but the post on the categories doesnt shows on mobile version, im ussin wptouch free version, did you know how to fix it ? or an other way to show the categories ?

  46. Jodi says:

    Thank you for this incredible tutorial. I was searching everywhere for it. I was curious to know, how would one style this into a bullet list where the posts would be surrounded by ? I’m not really a coder, more of a hack, but I keep managing to create syntax errors all over the place. Thank you for your assistance.

  47. Subash Aryal says:

    Thank you @wesbos, for this great tutorial. Really helped me get the stuff done. Looking forward to your more tutorials ๐Ÿ™‚

  48. Ajay says:

    Excellent Post…..


  49. Pingback: Displaying posts by category re-visited - gatekeepeR's Place

  50. Roee Yossef says:

    Hi Guys,

    Great Post !!!

    can you tell me how can i implement this on the search results page ? i want the search results to be sorted by category.

    Appreciate the help !

  51. Abdelrhman says:

    How to show all category posts, offset custom category posts.

  52. Nice post! I’ve been with WP for a while but this query will be very useful.

    I was thinking, what if I want to use this in the archive.php or category.php and show only the subcategories of the category I’m seeing in the moment? That would be a nice hack too.

  53. Andrew says:

    Still good. THANKS!

    Seems like passing a variable to the args, like you did with $cat_id, will NOT work with get_posts()…
    Why is it that with query_posts() it works?

  54. Pranav says:


    I am using your code to show category title and all its post below in an accordion format from a custom post type:-

    // loop through the categries
    foreach ($cats as $cat) {
    // setup the cateogory ID
    $cat_id= $cat->term_id;
    // Make a header for the cateogry
    echo “”.$cat->name.””;
    // create a custom wordpress query
    // start the wordpress loop!
    if (have_posts()) : while (have_posts()) : the_post(); ?>

    <a href="”>
    <?php echo '’; ?>

    This code is showing the categories right but showing all post from each category below the categories tile .

    Please help me fix this


  55. Jose Micky says:

    still not working !!!! do you know other ways to solve it???

  56. akram says:

    thank you alot ๐Ÿ™‚

  57. Alex says:

    @Michael Caputo – nice one dude, it was using the custom taxonomy as the key to define the category name and split the posts into their relevant sections. Lifesaver!

  58. Alex says:

    Sorry – @John Gardner. Cheers

  59. Santhosh says:

    How to make three widget in home page with sliding individuallyโ€ฆhere i made it three category like pre-lunch, under construction, ready to move in here if i click any category then it will open next page with all property listed in under that category how can do that plz help me here i am using wordpress realto theme

  60. i want to get post by portfolio but this is not working

  61. WONDERFUL Post.thanks for share..more wait .. ๐Ÿ˜‰

  62. Zaid Erikat says:

    Hay, thanks for this tutorial.
    I’m trying to do the same thing but get the posts of a custom post format and it’s not working, any one cane help me ???

  63. richard says:

    Hi, do you have a query post category by tabs?

  64. This tutorial is a life saver. Thanks a million from kenya.

  65. Mani says:

    Hi, thanks for the post, its so useful for us . But i would like to know , whether the list will be indexed by Google ?

    for eg : On my homepage of education site , i want to list posts by category wise .

    Entrance Exams
    Admit Cards

    So under Entrance Exams – the recent 5 posts on this category will be displayed but my question is will google index only the Title ( here Entrance exam ) or the links will also be updated ?

    Thanks .

  66. Santosh says:

    Great! Thanks a lot!

  67. Aaron Wiebe says:

    I had the same issue where it was looping every single post inside each category loop. Apparently you can’t use query_posts(‘cat=$cat_id’); but instead you can escape it by using query_posts(‘cat=’.$cat_id.”);

  68. Julie says:

    AWESOME!! Exactly what I needed! THANK YOU SO MUCH! ๐Ÿ™‚

  69. heowuayngon says:

    Thanks Wes.
    Very very helpful with me.

  70. Laxman says:

    Thanks ๐Ÿ™‚

  71. Thank a lot ๐Ÿ™‚ Was looking for it

  72. asiong says:

    Does anyone know how to paginate this categories. For example the categories exceed by 10 the page must paginate. Anyone please

  73. Matbakhoki says:

    Thank you so much for the example

  74. Eleodoro says:

    There is definately a lot to find out about this topic.
    I love all the points you’ve made.

  75. Boris says:

    Thank you so much!!!

  76. Jenny R. says:

    Thanks SO much for this clear explanation and code. It worked like a charm! I’m new to WP and I was creating a site for a client and they needed to see their blog categories separated-out on their home page and I couldn’t figure out how to get it done with widgets or CSS.

  77. Thank a lot Was looking for it
    John Gardner

  78. Mike Carr says:

    Thank you very much Wes! If you have a moment, I have a derivative question. I want to show the posts by category: but only the posts from today in each category. So far I can get all of the posts by category or all of the posts for today, but I cannot, so far, concatenate the two filterings. Any thoughts would be appreciated! Thank you.

  79. Chris Ames says:

    How would you exclude a specific category form the query?

  80. Angler says:

    I am Japanese.
    It was very helpful.
    Thank you.

  81. priya says:

    nice idea and great work.. Thanks for posting this info..

  82. Douglas says:

    This wouldn’t work with my Divi theme. I had to add some additional code so that it looked right.

    Hope this helps!


    // get all the categories from the database
    $cats = get_categories();

    // loop through the categries
    foreach ($cats as $cat) {
    echo "”;
    // setup the cateogory ID
    $cat_id= $cat->term_id;
    // Make a header for the cateogry
    echo “”.$cat->name.””;
    // create a custom wordpress query
    // start the wordpress loop!
    if (have_posts()) : while (have_posts()) : the_post();

    <a href="”>


    • Douglas says:

      This wouldn’t work with my Divi theme. I had to add some additional code so that it looked right.

      Hope this helps!

      // get all the categories from the database
      $cats = get_categories();

      // loop through the categries
      foreach ($cats as $cat) {
      echo "”;
      // setup the cateogory ID
      $cat_id= $cat->term_id;
      // Make a header for the cateogry
      echo “”.$cat->name.””;
      // create a custom wordpress query
      // start the wordpress loop!
      if (have_posts()) : while (have_posts()) : the_post();

      <a href="”>

  83. kalviseithi says:

    sometimes i had an issue for category wise. recently my webmaster tool is showing up html improvements those categories. Any solution..

  84. Silva says:

    How I can use the code to show all my createt projects from my portfolio and the tags instead of the categories?

    Thank you for your help.

  85. akash says:

    Hello sir,

    I want to display post by category in a coloum. please help me for this.

  86. This coding Will definitely Help for Students and Other Category Members

  87. Ahtasham Hussain says:

    You did the prefect one. I was looking around for this code from 2 days and i was almost fedup of it because of not getting the perfect one. Thank you so much sir.

  88. Seth Moder says:

    Thank you so much. This code is perfect and simple. I appreciate it.

  89. Patric K. says:

    Hi, this is a great method for showing all posts linked to a category.
    But Can you please tell me any method that I can show each and every post, even which is not linked to that category, on any page or category page in WordPress. I hope you got my question.

    Thanks, waiting for the answer.

Leave a Reply

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