Home » Functions » set_transient

Function Name: set_transient

Explanation: The set_transient function in WordPress is used to store a transient value in the database for a specified period of time. Transients are temporary data that can be used to cache expensive operations to improve the performance of your website. This function allows you to set a transient value with a specified key, a value, and an optional expiration time.

Usage: The set_transient function takes three parameters:

  1. $transient (string): The key or name for the transient value.
  2. $value (mixed): The value to be stored as the transient data.
  3. $expiration (int): Optional. The duration in seconds for which the transient should be cached. After this period, the transient will be automatically deleted.

Example Usage Code: Let’s say we want to retrieve some data from an external API and store it as a transient for 1 hour to reduce the number of API calls. We can use the set_transient function as follows:

$data = get_transient('external_api_data'); // Try to get the data from the transient

if ( false === $data ) {
    // If the transient doesn't exist, make the API call and store the data as a transient
    $api_data = make_external_api_call();
    set_transient('external_api_data', $api_data, 3600); // Set the transient for 1 hour (3600 seconds)
    $data = $api_data; // Use the API data directly

// Use the $data variable which can be either the transient data or the fresh API data
echo $data;

In the example above, the set_transient function is used to store the data returned from the external API as a transient with the key ‘external_api_data’ for a duration of 1 hour (3600 seconds). If the transient already exists, the function will update its value. Otherwise, it will create a new transient. The next time this code is executed within the 1-hour timeframe, the transient value will be retrieved without making another API call, thus improving the performance of the website.

Remember to adjust the expiration time according to your specific use case and caching needs.

Learn More on

Register an account to save your snippets or go Pro to get more features.