1

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 ?

1
  • 1
    This sounds simple, but, it has a performance cost, and the majority of oobvious solutions are crippled by the need for pagination which breaks them. There's also the problem of posts in multiple categories, and how to handle that. But I suspect there's more to this question that might give clues to an alternative solution to fixing the underlying problem
    – Tom J Nowell
    Commented Jul 16, 2020 at 9:05

2 Answers 2

0

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!

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.