How to use Transients

This page’s content is still “work in progress” – please bear that in mind whilst reading

There are 3 functions available to you (click on any for their parameter details)…

set_transient()

This allows you to save (or update) a Transient. There are 3 parameters…

  1. $transient – Transient name (required)
  2. $value – Transient value (required)
  3. $expiration – time until Transient expires, in seconds (optional)

The return value is either true or false, depending on the success of saving the Transient.

get_transient()

This allows you to fetch a Transient. There is just 1 parameter…

  1. $transient – Transient name (required)

The return value is either the Transient value OR false, if no Transient could be found. However, be aware of the following…

This should be checked using the identity operator ( === ) instead of the normal equality operator, because an integer value of zero (or other “empty” data) could be the data you’re wanting to store. Because of this “false” value, transients should not be used to hold plain boolean values. Put them into an array or convert them to integers instead.

WordPress Codex
delete_transient()

This allows you to delete a Transient. There is just 1 parameter…

  1. $transient – Transient name (required)

The return value is either true or false, depending on the success of deleting the Transient.

Transients on a multisite

If you’re using a multisite, there are 3 more available to you..

set_site_transient()
get_site_transient()
delete_site_transient()

The parameters for these are the same as the 3 non-network functions.

In a multisite set-up the first set of commands will allow you to control Transients at a sub-site level. The latter set of commands do the same but at the network level (i.e. they apply to all the sub-sites).

Tip: If you use the *_site_transient() functions on a non-networked site then they will behave the same as their standard *_transient() functions.

Using WordPress time constants

 There are a number of time constants in WordPress which make setting Transient expiries a lot easier…

MINUTE_IN_SECONDS
HOUR_IN_SECONDS
DAY_IN_SECONDS
WEEK_IN_SECONDS
MONTH_IN_SECONDS
YEAR_IN_SECONDS

So, for example, to set an expiry of a day you can simply use the ‘DAY_IN_SECONDS’ constant…

$return_value = set_transient( 'my_transient_name', $transient_value, DAY_IN_SECONDS );