Transients store data for a short time. If you have data that needs a long time to process but has some invariants then you might like to use transients. They can fasten things up.

Store slow queries

Imagine you have a query that is very slow. You might like to store the result for a short time:

$slow = get_posts( 'posts_per_page=-1' );

set_transient( 'something_unique', $slow, DAY_IN_SECONDS );

Or a even longer time if it is really persistent. There are some constants in the WordPress Core (see “wp_initial_constants” function) that will help you:


Use them as the third argument for expiration time. If you don’t then your site will slow down – I guarantee that.

Wrong usage can slow things down

So in general you decide how long something shall be stored and with this few lines you can fasten things up:

$slow = get_transient( 'something_unique' );

if ( false === $slow ) {
  // no data in transient => regenerate
  $slow = get_posts();
  set_transient( 'something_unique', $slow );

// ...

But wait, there is a huge problem with that code. The lifetime has not been set, so it will default to zero. A transient that persist untill the dawn of the database. WordPress sees that and will do weird stuff.

The transient will be treated as if it is always needed. WordPress sets a flag to autoload it with every visit of your blog or website. If you have a huge amount of data there, then your website will slow down. So better tell WP how long the cached data is needed. In that case WordPress won’t load the transient on every page view:

set_transient( 'something_unique', $slow, DAY_IN_SECONDS );