Skip to content

Instantly share code, notes, and snippets.

@charmoney
Forked from vanaf1979/maybe-cache.php
Last active July 9, 2024 20:04
Show Gist options
  • Save charmoney/3eae5d1cbad1ea80f89b66bd2c3b6029 to your computer and use it in GitHub Desktop.
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/
<?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