Want VIP access? Get the latest tutorials, videos, giveaways and more!

×

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.

<?php
/* 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.

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

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

			<?php
			// 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
					query_posts("cat=$cat_id&posts_per_page=100");
					// 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.

70 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? http://ow.ly/4p2gS

    • 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:

    query_posts(“cat=$cat_id”);
    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?

    Thanks!

  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
    http://www.themodelwe.com under all agency’s menu
    thanx again:)

  16. 0001 says:

    sorry mis type before here is the url : http://www.themodelweb.com/modeling-agencys/

    and thanx a bunch one more time…
    pece
    tmw

  17. kAlAi says:

    Hai,
    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?

    Thanks

  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?

    cheers

  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: http://mtspacewebdesign.com/blog/listing-wordpress-custom-post-types-by-category/

  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.

    THanks

  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.

    Syed.

  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?

    Thanks,
    JanD

  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.

    Tnx,

  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.

    -Efrem

  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…..

    Thanks….

  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:

    Hi,

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

    ‘acme_menu’));
    // 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
    query_posts(“cat=$cat_id&posts_per_page=100″);
    // 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

    Thanks
    pranav

  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

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>