Improve Performance Using WordPress Transients to Cache a Database Query

One of my goals this year is to level up as a developer. I know this isn’t a good SMART goal, but its still a something I’m shooting for. I’m on the lookout for simple yet powerful ideas that I can implement in my daily programming workflow.

One example of a simple yet powerful idea is utilizing the WordPress Transients API to cache a resource intensive database query. The Transients API is a simple and standardized way of storing cached data in the database temporarily.

The example code in this gist is directly from Brad Campeau-Laurion’s presentation at LoopConf 2017 on Code Review and Why It Matters. I had yet to see a good example of how to use transients for caching a WordPress query. I knew it was important for performance reasons, but wasn’t quite sure how to implement it.

You can modify the query as needed to fit your needs. I’ve been using it for storing large WP Query calls. You can also store the results of 3rd party API calls using this technique.

Measuring Light Bulb Moments

I know this wasn’t the point of his talk, but with this small bit of example code the use case for WordPress Transients now makes sense to me. You never know when the light bulb moment will be. I’ve had many light bulb moments on my programming journey, but hopefully this year I’ll have more than normal.

I think by writing this post I’ve figured out how to measure my “level up as a developer” goal. More light bulb moments this year than in year’s past.

Now that’s a SMART goal.

Leave a Reply

%d bloggers like this: