Use Transients API Caching and Speed Up Your WordPress Theme.
The Transients API in WordPress is an effective method for saving cached data in the database. It allows us to take resource-intensive queries and store them in short-term caches to enhance performance. Transients are short-term. For example, after a specified period of your time, the cached information will be removed and re-cached, or modified.
This quick demonstration will walk you through how to use transients in your WordPress development.
Dealing with transients is straightforward. There are just three functions that you need to know about:
set_transient() – Used to store data in a cache
get_transient() – Used to retrieve the cached data
delete_transient() – Used to delete cached data
Usage Transients
1. Saving Transients
set_transient()
function used to save or update the value of a transient in the cache.
<?php
set_transient( $transient, $value, $expiration );
?>
$transient
is a unique key name for your cached data.
$value
Data to save, either a regular variable or an array/object. The API will handle the serialization of complex data.
$expiration
The maximum of seconds to keep the data/value before refreshing.
Example: Saving the
object for 12 hours:$query_results
set_transient( 'query_results', $query_results, 60*60*12 );
Using Time Constants
In WordPress 3.5, few time constants were introduced for easy time express.
MINUTE_IN_SECONDS = 60 (seconds)
HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS
DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS
WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS
YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS
Example of Time Constants:
set_transient( 'query_results', $query_results, 12 * HOUR_IN_SECONDS);
2. Fetching Transients
function is used to get the saved transient.get_transient()
<?php get_transient( $transient ); ?>
Here $transient
is a Unique transient key name. If the transient does not exist or does not have any value, then it will return a false
value.
3. Removing Saved Transients
delete_transient()
function used to delete manually the transient key before it expires.
delete_transient( $transient );
the unique key name used when saving with $transient
.set_transient()
The function below will demonstrate basic usage of transients:
function qirolab_transient_demo() {
// get the cached data
$data = get_transient('sample_trans');
// check to see if data was successfully retrieved from the cache
if( false === $data ) {
// do this if no transient set
$data = 'This is the data stored in the transient';
// store the data and set it to expire in 10 seconds
set_transient('sample_trans', $data, 10);
}
// this will output "This is the data stored in the transient" regardless of whether a the data was retrieved from the cacue or not.
echo $data;
}
add_action('admin_notices', 'qirolab_transient_demo');
Please login or create new account to add your comment.