Display multiple posts from each taxonomy

Displaying multiple posts from single category

Or simply: how to show multiple posts from each category in an ordered way in WordPress?

A lot of times I saw the question of how to display 2 or more posts from single category and stack them nicely in WordPress. The first thing that comes to mind is, of course is WP_Query. And true enough, we’ll need the query to get our posts. But WordPress default query class will only return posts, ordered in a certain way. Sadly, you cannot specify to query specific amount of posts from each taxonomy. It would be a cool thing to have, and who knows, maybe we’ll have it somewhere in the future, but for now we need to implement another way of doing this.

By no means is the technique I’ll show you here super advanced, but it takes some steps to execute properly.

In your page template, or archive, category, taxonomy or home page even, you’ll need to first fetch all the categories. You can fetch categories from custom post type, but here I’ll fetch just ordinary built in categories.

Notice the taxonomy  parameter. You can change it to your custom taxonomy if you wish. Since get_categories() returns array of categories, we’ll create a foreach  loop and in that loop create our query. And that’s basically it. The whole thing looks like this:

Now you can create your own preferred layout, add more arguments to your query etc. It’s all up to you.

Granted this is not the most friendly piece of code because it runs queries inside foreach, so it’s like multiple queries withing queries within queries (queryseption? XD), but it’s all we can do for now. Plus we are only retrieving back 2 posts, so it’s not a taxing query to run.

The get_categories()  function can take other arguments, for instance

It’s up to you to sort them how you like. You can manipulate the resulting array using php if you wish, but I think you have all you need here.

That’s it for today, had to cut it a bit short and simple, have Swedish exam next week so I had to study for that, plus I have a plugin that I’m currently developing. I hope it will be out soon, so that I can put it here and on WP.org as well.

If you have any kind of questions feel free to leave them in the comments below, until next time, happy coding!

Also published on Medium.

Join the Discussion