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 get_transient($transient); // Remove data delete_transient($transient);
- $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() { delete_transient('my_widget_query_results'); }
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.