Use Transients API Caching and Speed Up Your WordPress Theme.

Use Transients API Caching and Speed Up Your WordPress Theme
The Transients API in WordPress is an effective means 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 really need to know about:

  1. set_transient() – Used to store data in a cache
  2. get_transient() – Used to retrieve the cached data
  3. delete_transient() – Used to delete cached data

Using Transients


1. Saving Transients

set_transient() function is used to save or update the value of a transient in cache.
Syntax

$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 serialization of complex data.
$expiration The maximum of seconds to keep the data/value before refreshing.

Example: Saving the $query_results object for 12 hours

Using Time Constants
In WordPress 3.5, few time constants were introduced for easy time express.

Example of Time Constants:

2. Fetching Transients

get_transient() function is used to get the saved transient.
Syntax

Here $transient is a Unique transient key name. If the transient does not exist or does not have any value, then it will return false value.

3. Removing Saved Transients

delete_transient() function used to delete manually the transient key before it expire.
Syntax

$transient the unique key name used when saving with set_transient().

The function below will demonstrate a very basic usage of transients:

Leave a Reply

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