Caching queries to improve performance

This is available as a separate plugin: Display Posts – Transient Cache

Some users will build very complex queries involving multiple taxonomy and meta queries. These can be computationally expensive to run, and running the query on every uncached pageload is not necessary.

We can store the output of the shortcode in a transient – a site option that expires after a certain amount of time.

We’ll use the pre_display_posts_shortcode_output hook to hop in before the shortcode runs to check if the current shortcode’s output is already cached, and display that instead if it’s available.

We’ll add two new parameters to the Display Posts shortcode:

  • transient_key – This should be a unique key you define. Each key will be cached separately, so if you’re using the same shortcode on multiple pages you can use the same key for each one (cache it once rather than separately)
  • transient_expiration – This is how long (in seconds) the data should be cached. You can specify a number (ex: 86400), or use one of the time constants to make it easier to read (ex: WEEK_IN_SECONDS). You can also multiply the constants (ex: 2 * DAY_IN_SECONDS ).


[display-posts transient_key="be_recent_posts" transient_expiration="DAY_IN_SECONDS"]


View the code here in the GitHub repo for the Display Posts – Transient Cache plugin.

Filters used:

Published by Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributor to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.