Skip to content

Instantly share code, notes, and snippets.

@un1ko85
Created July 4, 2013 11:27
Show Gist options
  • Save un1ko85/5926931 to your computer and use it in GitHub Desktop.
Save un1ko85/5926931 to your computer and use it in GitHub Desktop.
Wrapper around get_posts that utilizes object caching
/**
* Wrapper around get_posts that utilizes object caching
*
* @access public
* @param mixed $args (default: NUL)
* @param bool $force_refresh (default: false)
* @return void
*/
function get_posts_cached( $args = NULL, $force_refresh = false ) {
$cache_incrementor = wp_cache_get( 'get_posts_cached', 'cache_incrementors' );
if ( !is_numeric( $cache_incrementor ) || true === $force_refresh ) {
$now = time();
wp_cache_set( 'get_posts_cached', $now, 'cache_incrementors' );
$cache_incrementor = $now;
}
$cache_key = 'get_posts_cached_' . $cache_incrementor . '_' . md5( serialize( $args ) );
$cache_group = 'get_posts_cached';
$posts = wp_cache_get( $cache_key, $cache_group );
if ( false === $posts || true === $force_refresh ) {
$posts = get_posts( $args );
if ( count( $posts ) < 11 ) // we don't want to cache too much
wp_cache_set( $cache_key, $posts, $cache_group );
}
return $posts;
}
/**
* Invalidate get_posts_cached stored values.
*
* @access public
* @return void
*/
function invalidate_get_posts_cache( $post_id ) {
$args = array( 'include' => array( $post_id ) );
get_posts_cached( $args, $force_refresh=true );
}
add_action( 'save_post', 'invalidate_get_posts_cache', 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment