I am not sure if this has been answered before, but vigorous googling has not led me anywhere so far.
I have a wordpress site where I would like to display all posts as usual, ordered by date. However, instead of setting a limit on the total number of posts displayed, I would like to set a limit on each category.
For instance, if I have two categories FOO and BAR, I want WordPress to display all, but at most 5, posts from both FOO and BAR. The posts should still be ordered by date, and I mean that any post from FOO that was posted before one from BAR appears first and vice versa.
Specific problem: There is one post in the category FOO from last year, then 20 entries in BAR since then and now I am adding another post in the category FOO. Usually, WordPress with a post limit of 10 would display this most recent FOO entry and 9 more BAR entries. However, I would like it to display both my FOO entries and the 5 most recent BAR entries. Only after I add 4 more FOO entries, the FOO entry from last year will no longer be displayed.
What is the best, most clean and maintainable way to achieve this?
I would be very grateful for any help.
Given that there seems no other solution that doing an insane amount of queries, I devised the following, added to
functions.php
.In this solution, I only fetch the ids of all relevant posts first, instead of all the contents and then perform a query to retrieve the actual data. I prefer this solution so far because I can use it without even touching my main loop, which is modified via the hook
pre_get_posts
.I would still prefer a solution that is a little faster, i.e. one that only performs a single query.
Untested, but this should get you started:
You just need to use
get_categories
,get_posts
with order by date and useforeach
to show the results.Here is: