TransWikia.com

Group Posts by Category in Monthly Archive

WordPress Development Asked by Zero Goki on October 30, 2021

I’m using the monthly archives on my website but my loop is currently displaying my posts this way :
Category title
Post title 1
Category title
Post title 2
etc..

What I want to do is displaying all the posts from the active months grouped by categories so event if there is 4 posts in the categories, it will look like this :
Category title
Post title 1
Post title 2
Post title 3

Other Category title
Post title 4

Is there a simple way to group the posts this way ?

2 Answers

Thanks, I don't need pagination as there is just few posts every month and there is also just few categories. I'm gonna try this and tell you if that works ! Many thanks again

Answered by Zero Goki on October 30, 2021

So due to issue mentioned by @Tom J Nowell doing this is actually a bit more complicated because it depends on how you want to sort the posts and if you want pagination. If you sort the posts by date, then even if you could group by category, each page of results would likely still have a few from each category.

There is an easy answer though, if you don't have too many posts and don't want pagination, which is to loop through the categories and output all the posts in each category. There are examples here and here, the simplest of which looks like this:

$categories = get_categories( array ('orderby' => 'name', 'order' => 'asc' ) );

foreach ($categories as $category){

   echo "Category is: $category->name <br/>";

   $catPosts = new WP_Query( array ( 'category_name' => $category->slug, 'orderby' => 'title' ) ); 

   if ( $catPosts->have_posts() ){

       while ( $catPost->have_posts() ){
          $catPost->the_post();
          echo "<a href='the_permalink()'>the_title()</a>";
       }

   }//end if

} //end foreach

wp_reset_postdata();

You need to edit this to render the category heading and posts how you want them.

The downside of this is that it'll run more queries - one per category, and then if you have a lot of posts this page will be long!

Answered by mozboz on October 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP