How to use the WordPress Transient API

The Transient API is a way of storing data in the WordPress database temporarily. Giving data a shelf life will ensure it doesn’t live longer than a given amount of time. You could store the result of an expensive query or some data that has been processed. Transients are saved in the wp_options database table. 3 functions help us get the job done.

  • set_transient()
  • get_transient()
  • delete_transient()

Setting a transient

set_transient() is used to set or update data. The function accepts the name of the transient, a value and a number of seconds until expiry. Transient names and values are expected to not be SQL escaped.

set_transient( 'query_result', $query_result, 900 )

The name must be 172 characters or less. You might be wondering why only 172 when the option_name column in the wp_options table can hold up to 191 characters. The 172 figure isn’t arbitrary. WordPress will prefix transient names with “_transient_” and also “_transient_timeout_” if an expiry is given.

The value can be an integer, a string, an array or even an object. WordPress will handle serialisation of complex data for us.

The last argument is an optional integer and indicates the number of seconds until expiry. This is 0 by default. 0 indicates no expiry.

Getting a transient

get_transient() is used to get data. The function accepts the name of the transient to get.

$data = get_transient( 'query_result' )

If the transient doesn’t exist, has expired or doesn’t have a value then the function will return false.

It’s important to point out that transients can disappear before they are due to expire so never assume a transient is in the database.

Deleting a transient

delete_transient() will delete a transient. The function accepts the name of the transient to be deleted.

delete_transient( 'query_result' )

The function will return true if successful and false if not. No action is taken if the transient doesn’t exist.


If you’re running WordPress in network mode, “_site_” functions can be used instead.

  • set_site_transient()
  • get_site_transient()
  • delete_site_transient()

These functions are essentially the same as their single-site counterparts. However, WordPress uses the “_site_transient_” and “_site_transient_timeout_” prefixes for site transients so names must be 167 characters or less if using these functions.


Transients that expire aren’t loaded when WordPress starts.

Posted by on .


<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>