Skip to content

Instantly share code, notes, and snippets.

@rheinardkorf
Last active December 7, 2020 11:32
Show Gist options
  • Save rheinardkorf/12e7f521881bd1987d84b58a5f6e8b8d to your computer and use it in GitHub Desktop.
Save rheinardkorf/12e7f521881bd1987d84b58a5f6e8b8d to your computer and use it in GitHub Desktop.
Example using WP caching.
<?php
// This example assumes an object cache is available. If its not, transients WITHOUT EXPIRATION will be used.
$cache_key = 'unique_prefix_' . md5( $variables );
$results = wp_cache_get( $cache_key );
if ( false === $results ) {
$results = $wpdb->get_var( $wpdb->prepare("SQL STATEMENT HERE", $variables['here'], $variables['etc'] ));
wp_cache_set( $cache_key, $results );
}
<?php
// Define a unique group for your plugin/feature.
$cache_group = 'my-unique-cache-group';
// A hash of the variables makes for a good key.
$cache_key = md5( wp_json_encode( $variables ) );
// Attempt the get the results from object cache if available; or from a transient.
$results = wp_using_ext_object_cache() ? wp_cache_get( $cache_key, $cache_group ) : get_transient( $cache_group . '-' . $cache_key );
// If no results are retrieved.
if ( false === $results ) {
// Get the results as intended. This is an example. This code will not execute!
$results = $wpdb->get_var( $wpdb->prepare("SQL STATEMENT HERE", $variables['here'], $variables['etc'] ));
// If object cache is available...
if ( wp_using_ext_object_cache() ) {
// Cache without expiration as this is the job of the cache provider.
wp_cache_set( $cache_key, $results, $cache_group );
} else {
// Set a transient that expires. In this case, a month.
set_transient( $cache_group . '-' . $cache_key, $results, MONTH_IN_SECONDS );
}
}
// Proceed as normal...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment