Cache Any Expensive Result With One Function
Adds a wpide_remember() helper that returns a cached value if there is one, or runs your function, stores the result for a set time and returns it, which makes caching slow queries and API calls a one-liner.
Opens WPIDE on
Code
if ( ! function_exists( 'wpide_remember' ) ) {
function wpide_remember( $key, $seconds, callable $callback ) {
$cache_key = 'wpide_rmb_' . md5( $key );
$cached = get_transient( $cache_key );
// Wrapped so that false and empty results are cached too.
if ( is_array( $cached ) && array_key_exists( 'value', $cached ) ) {
return $cached['value'];
}
$value = call_user_func( $callback );
if ( ! is_wp_error( $value ) ) {
set_transient( $cache_key, array( 'value' => $value ), max( 1, (int) $seconds ) );
}
return $value;
}
function wpide_forget( $key ) {
return delete_transient( 'wpide_rmb_' . md5( $key ) );
}
}
Notes
Example $top = wpide_remember( 'top_posts', HOUR_IN_SECONDS, function () { return get_posts( ... ); } ); call wpide_forget( 'top_posts' ) to clear it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.