So i have this technicall dilemma:
I have a WordPress site, with more than 50 categories (and rising). I want to get just the six categories with the newest article in them, and -if i get this right- i can’t do it with a single typical WP Query, i’ll have to improvise:
a) get from the database the last 200-300 posts, and by elimination in PHP filter by category, and show the six last updated categories, or
b) get from the database all my categories, and for each category ask again the database the last article by date – and show the six last updated categories.
i know that the first solution is not very safe, and will strech a little my server calculating with PHP, but the second will have more than 50+1 queries (and rising).
Considering that the site i’m working on has a couple of million visitors each month, which one do you think will give, from a technical point of view, the less stress to my servers?
Or i’m missing an more obvius solution?
Thanks for your time! 🙂
2
Answers
Can,t you just join the articles and sort by the joined table ordered by date desc?
Something like:
Select from categories c
Left join articles a on a.category = c.id
Order by a.date desc group by c.id limit 6
Every time you post something, you could save the taxonomy’s
name
/slug
/id
in a transient on publishing/updating throughset_transient()
andsave_post
action hook.Saving the data as an array and slicing it once it reach 6… array_search before updating…
To display them you would simply loop through the transient’s value and
get_taxonomy()
or build a customWP_Query
looping through each of them.Which would avoid you a lot of queries. Pretty much none…
here is an untested demo: