Optimized related posts
I used to use this snippet to fetch related posts:
It looks up all terms in a given taxonomy associated with the current post. If it finds any, it’ll loop over them and, for each term, execute a new database query looking after other posts sharing that taxonomy term.
Last week, I worked on a website that was doing too many DB queries, forcing me to go through the code and optimize where possible.
I noticed the snippet above was to blame for a lot of those queries and decided to rewrite a less database-intensive version. This is what I came up with:
The main difference is that instead of looping over each taxonomy term and firing off a new query, I simply do a new
WP_Query with the tax_query param (Line 22). This results in only a single database query, and saved me about 60 queries per page.
My question is: do you see anything wrong with my snippet? From what I can tell it does exactly the same thing.
If not, I'd like to post an article on my blog explaining why this is a better approach, and maybe trawl the web a bit trying to help people learning about the tax query thing, because I'm seeing the first snippet, the one with a query for each loop iteration, almost everywhere people ask for a related posts snippet.