Skip to Content
Menu

transient()

Convenient pattern to cache data using WordPress transients and the WordPress object cache.

PHP May 9, 2021

Usage

PHP
nebula()->transient($name, $function, $expiration, $fresh)

Parameters

$name
(Required) (String) The name to use for the caches
Default: None

$function
(Required) (Function or String) The function itself, or the name of the function
Default: None

$parameters
(Optional) (Array) An array of parameters to be made available to the function
Default: array()

$expiration
(Optional) (Integer) How long to cache the data
Default: null

$fresh
(Optional) (Boolean) Bypass the transient to retrieve "fresh" data
Default: false

Parameter Notes

The $parameters parameter must be passed as an array when used! This parameter can be left off completely when not needed.

A null expiration means the transient will never expire until deleted. Don’t forget about the helpful WordPress time constants such as HOUR_IN_SECONDS, DAY_IN_SECONDS, WEEK_IN_SECONDS, MONTH_IN_SECONDS, YEAR_IN_SECONDS.

Passing $fresh as true will bypass the transient, but not the object cache. That means that the function will at most run once per load– great for when the function is called multiple times in the same page load.

Return null inside of the function to bypass storing anything into either cache. Not returning at all would also have the same result.

Request or provide clarification »

Examples

Write the function inline

PHP
$data = nebula()->transient('Get Hello Array', function(){
    return array('hello'); //Do an expensive task
}, HOUR_IN_SECONDS);

Reference a function by string

PHP
$data = nebula()->transient('Get Hello Array', 'my_named_thing', HOUR_IN_SECONDS);

//Then somewhere else define the function:
function my_named_thing(){
    return array('hello'); //Do an expensive task
}

Bypass storing anything into the cache on error

PHP
$data = nebula()->transient('Get Hello Array', function(){
    if ( is_error($example) ){
        return null; //Return null or just return will not store anything in either cache
    }

    return array('hello'); //Do an expensive task
}, HOUR_IN_SECONDS);

Use an anonymous function with parameters

PHP
$post_type = 'whatever'; //Example
$count_posts = nebula()->transient('do my thing', function($data){
    return example_function($data['post_type']); //Use the passed parameter here
}, array('post_type' => $post_type), YEAR_IN_SECONDS); //Remember: parameters must be passed as an array!

Reference a function by string with parameters

PHP
$post_type = 'whatever'; //Example
$count_posts = nebula()->transient('do my thing', 'my_custom_function', array('post_type' => $post_type), YEAR_IN_SECONDS); //Remember: parameters must be passed as an array!

function my_custom_function($data){
    return example_function($data['post_type']); //Use the passed parameter here
}

Additional Notes

This function is mostly for the convenient pattern of checking the transient and the object cache. If your usage of the transient storage is different than simply getting/setting data to a variable, you may need to write the transient/wp_cache directly.

Note: Using the ?debug query parameter will clear/bypass the transient.

Was this page helpful? Yes No


    A feedback message is required to submit this form.

    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

    Located in /libs/Utilities/Utilities.php on line 655.

    No Hooks

    This function does not have any filters or actions available. Request one?
    PHP
            public function transient($name, $function, $parameters=array(), $expiration=null, $fresh=false){
                //If the parameters varibale is not passed at all, use it as the expiration. This could be avoided by listing the parameters by name when calling this function...
                if ( is_int($parameters) ){
                    $expiration = $parameters;
                    $fresh = $expiration;
                    $parameters = array(); //And reset the $parameters variable to be an empty array
                }
    
                $data = get_transient($name);
                if ( !empty($fresh) || empty($data) || $this->is_debug() ){
                    $data = wp_cache_get($name);
                    if ( empty($data) ){ //This does not get a "fresh" option because we always only want it to run once per load
                        if ( is_string($function) ){
                            $data = call_user_func($function, $parameters); //If the function name is passed as a string, call it
                        } else {
                            $data = $function($parameters); //Otherwise, assume the function is passed as an actual function
                        }
    
                        if ( is_null($data) ){
                            return false; //If the function does not return, do not store anything in the cache
                        }
    
                        wp_cache_set($name, $data); //Set the object cache (memory for multiple calls during this current load)
                    }
    
                    set_transient($name, $data, $expiration); //Set the transient (DB to speed up future loads)
                }
    
                return $data;
            }
    

    Override

    This function can not be short-circuited with an override filter. Request one?