Cache data with WordPress Transient API

With WordPress transient API you can cache data in the database by giving it a unique identifier and an optional expire time after it will be deleted.

There are basically three functions in this API.

// Save data
set_transient($transient, $data, $expiration);

// Fetch data

// Remove data
  • $transient – a unique identifier
  • $data – the data to cache in the database
  • $expiration (optional) – seconds until the data should expire

The get_transient function will return false if the data has expired.

An example of how to use WordPress transient API

Lets make up a very basic example. Say that you have a widget that query the database for the 5 latest posts. To minimize the load on the database you can cache the results for a period of time. In this example we set the expiration time to 1 hour.

The php function can look something this.

// Get cached data, if any
if (false === ( $my_widget_query_results = get_transient('my_widget_query_results') ) ) {
    // If no data in cache, regenerate the data and save it
     $my_widget_query_results = new WP_Query('order=desc&post_count=5');
     set_transient('my_widget_query_results', $my_widget_query_results, 60*60*1);

// Then use the data as normal

Alternatively, you can skip the expiration parameter and use action hooks instead to delete the cached data. By doing it this way you will only regenerate the data when you actually need to. In our example, when a new post is published.

add_action('publish_post', 'remove_my_widget_query_results);

function remove_my_widget_query_results() {

About Fredrik Malmgren

Fredrik Malmgren is an entrepreneur, project manager and developer specialized in WordPress. Read more about me or get in contact with me. You can also find me on Twitter. (@fredrikmalmgren).
This entry was posted in Tutorials, WordPress and tagged , , , , , , . Bookmark the permalink.

1 Response to Cache data with WordPress Transient API

  1. RS says:

    Have you seen any issues that are causing transients to not be deleted when they expire? I’m seeing wp_options tables filling with them, and not expiring when they’re supposed to.

Leave a Reply

Your email address will not be published. Required fields are marked *