Last active
August 29, 2015 14:07
-
-
Save jtsternberg/08c4b35187dcd71f5848 to your computer and use it in GitHub Desktop.
tlc-transients helper functions
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 | |
// Include tlc lib | |
require_once WPMU_PLUGIN_DIR . '/wp-tlc-transients/tlc-transients.php'; | |
/** | |
* Use in place of `get_posts` | |
* | |
* @param array $args Array of get_posts arguments | |
* @param integer $time Amount of time before cache expires | |
* | |
* @return array Array of post objects | |
*/ | |
function wds_cache_get_posts( $args = array(), $time = HOUR_IN_SECONDS, $cache_empty = true ) { | |
$posts = wds_cache_wp_query( $args, $time, $cache_empty, 'get_posts' ); | |
return ! empty( $posts ) ? $posts : 'no'; | |
} | |
/** | |
* Use in place of `new WP_Query` | |
* | |
* @param array $args Array of WP_Query arguments | |
* @param integer $time Amount of time before cache expires | |
* @param string $callback Callback function. (if you don't want to use WP_Query) | |
* | |
* @return WP_Query object | |
*/ | |
function wds_cache_wp_query( $args = array(), $time = HOUR_IN_SECONDS, $cache_empty = true, $callback = '_wds_get_original_wp_query' ) { | |
$trans_key = md5( 'cache_query' . $callback . serialize( $args ) ); | |
if ( defined( 'WP_DEBUG' ) && WP_DEBUG && isset( $_GET['cache_debug'] ) ) { | |
error_log( '$args: '. print_r( $args, true ) ); | |
} | |
// cache query | |
$tlc = tlc_transient( $trans_key ) | |
->updates_with( $callback, array( $args ) ) | |
->expires_in( $time ); | |
// get cache query | |
$query = $tlc->get(); | |
// Request a new fetch if result is empty? | |
if ( ( empty( $query ) || is_a( $query, 'WP_Query' ) && ! $query->have_posts() ) && ! $cache_empty ) { | |
$query = $tlc->fetch_and_cache(); | |
} | |
return $query; | |
} | |
/** | |
* Don't call directly, use wds_cache_wp_query | |
*/ | |
function _wds_get_original_wp_query( $args = array() ) { | |
return new WP_Query( $args ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment