Skip to Content


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

PHP April 14, 2021


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


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

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

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

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

Parameter Notes

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.

Request or provide clarification »


Write the function inline

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

Reference a function by string

$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

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.

Source File

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

No Hooks

This function does not have any filters or actions available. Request one?
        public function transient($name, $function, $expiration=null, $fresh=false){
            $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); //If the function name is passed as a string, call it
                    } else {
                        $data = $function(); //Otherwise, assume the function is passed as an actual function

                    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;


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