Don’t Cache WP_Query Objects (and Why Not)
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
“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:
- The WordPress Transients API serializes the values it stores, which is going to be very ugly if you’re storing an enormous
- 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
SAVEQUERIESwas turned on.”
- 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
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