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!
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!
Glad I could help! Hopefully some others find it useful as well
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
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.
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.
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.
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.
Pingback: WordPress Community Links: Akismet the dog edition | WPCandy
Pingback: WordPress Community Links: Akismet the dog edition | Technology Story
Just throwing in another thank you, exactly the snippet of code I needed!
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
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
);
thaaaank u man v much
exactly the snippet of code I needed
This is great. It’s really nice to have the video in addition to the code. Thank you!
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?
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.
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
thanks to many , i like your code and use , this is very use ful code for me ,
thanks to once again many many
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!
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!!
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
thanx for the briliant elegant and simple wel documented tutorial.. se implemented
http://www.themodelwe.com under all agency’s menu
thanx again:)
sorry mis type before here is the url : http://www.themodelweb.com/modeling-agencys/
and thanx a bunch one more time…
pece
tmw
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
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?
Finding this post probably saved my job.
Thanks so much!
How to exclude a categody id ??
Thank God! Your a life Saver!
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
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?
Thanks for quick example…
what can I do to just select one category and show only the posts of that specific category?
nevermind I got it
great job … thx
WOW! it’s work great for me!!! Bravo!
Thanks Author!
who have problem with some post show and load more memory. add wp_reset_query (); before the last closing php ?>
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
Can you show how to set this up with a custom post type?
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/
what if you have posts that are in different categories? You would end up with repeated posts.
Great Work…..!!
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
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
Pingback: Wordpress category loop, how to hide cats with no posts? - feed99
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.
Thanks for the good example..
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.
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
Great job, wesbos.
Can anyone can help me out with making the category title a link to appropriate category?
Something like:
"> ...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,
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!
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
I had a spelling mistake, the argument should be
posts_per_pageand notpost_per_pageim 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 ?
WP touch is a theme, so any customizations to your normal theme are lost on the wp touch theme.