Last active
July 9, 2024 20:00
-
-
Save vanaf1979/2a0d5b6b1bd16c9be2ed44d758c3ae09 to your computer and use it in GitHub Desktop.
Snippet #008 Using transients to cache data. https://since1979.dev/snippet-008-using-transients-to-cache-data/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* maybeCache. | |
* | |
* Check if transient cache exist, else set it, | |
* | |
* @see https://since1979.dev/snippet-008-using-transients-to-cache-data/ | |
* | |
* @uses get_transient() https://developer.wordpress.org/reference/functions/get_transient/ | |
* @uses is_callable() https://www.php.net/manual/en/function.is-callable.php | |
* @uses wp_die() https://developer.wordpress.org/reference/functions/wp_die/ | |
* @uses call_user_func() https://www.php.net/manual/en/function.call-user-func.php | |
* @uses set_transient() https://developer.wordpress.org/reference/functions/set_transient/ | |
* | |
* @param String $cahce The name of the transient | |
* @param Int $time The transient timeout | |
* @param Callable $callback The callback function | |
* @return Mixed | |
*/ | |
function maybeCache(String $cache = '', Int $time = 7200, Callable $callback = null) | |
{ | |
if ($cachedData = get_transient($cache)) | |
return $cachedData; | |
if (!$callback || !is_callable($callback)) | |
wp_die('No (valid) callback function provided.'); | |
set_transient($cache, $data = call_user_func($callback), $time); | |
return $data; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment