-
-
Save charmoney/3eae5d1cbad1ea80f89b66bd2c3b6029 to your computer and use it in GitHub Desktop.
Snippet #008 Using WordPress 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 | |
/** | |
* Check if transient cache exist, else set it. | |
* | |
* Refactored by https://github.com/charmoney for PHP_CodeSniffer WordPress Standards compliance and WP_Error handling. | |
* | |
* @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 $cache_key The name of the transient. | |
* @param int $time The transient timeout. | |
* @param callable $callback The callback function. | |
* @return mixed Cached data or WP_Error. | |
*/ | |
function maybe_cache( string $cache_key = '', int $time = 7200, callable $callback = null ) { | |
// Return cached data if possible. | |
$cached_data = get_transient( $cache_key ); | |
if ( false !== $cached_data ) { | |
return $cached_data; | |
} | |
// Invoke callback function if needed. | |
if ( ! $callback || ! is_callable( $callback ) ) { | |
wp_die( 'No valid callback function provided.' ); | |
} | |
$data = call_user_func( $callback ); | |
// Cache anything except a \WP_Error. | |
if ( ! is_wp_error( $data ) ) { | |
set_transient( $cache_key, $data, $time ); | |
} | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment