Don’t Cache WP_Query Objects (and Why Not)

cache pallets | cache wp_query

Recently, I was working on site speed for a client with one page that makes a large number of custom database queries through WordPress’s WP_Query API.

“Gee,” I thought, “these WP_Querys are so slow, maybe I should find a way to cache them?” I took something like “how to cache wp_query” to Google and found the linked article.

It turns out you shouldn’t cache WP_Query objects at all, for a few good very reasons:

  1. The WordPress Transients API serializes the values it stores, which is going to be very ugly if you’re storing an enormous WP_Query object.
  2. Serializing the object also stores some scary things into the database: “our database credentials, all other database settings, as well as the full list of SQL queries along with their timing and stacktraces if SAVEQUERIES was turned on.”
  3. Perhaps most importantly: for technical reasons you should simply read from the source, the unserialized query must then query every post’s metadata separately—resulting, in most cases, in an enormous proliferation of queries to the database per page load when the whole point was to cut down on those.

tl;dr: Don’t cache your WP_Query objects!

As a broader note, it’s really nice when a tech resource doesn’t merely tell you how to do something, but will actually tell you if it’s a bad idea and what to do instead. Like a new car owner from 100 years ago looking for “where to hook the horse up,” people Googling for code often need knowledge that’s quite a bit broader than their specific question. We aim to be a resource that points you in the right direction, and cheers to Pressjitsu for being one in this case.

Image credit: Sam Beebe


2 Responses

Comments

  • Igor Beni? says:

    If you need to cache it, then don’t cache the actual query. In some projects, I have built an array with all the information I would need and then use the Transient API to cache it. If there is no such array, run the WP_Query once more.

    I have also read somewhere that you could also build the entire HTML and cache it like that but I am not sure if that is a better way.

  • Mat says:

    So…. make extra large queries on the fly?

Add a comment

(required)

(required)

(optional)