Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
WordPress: Cache patterns for complex queries
<?php
/**
* Retrieve a WP_Query object
*/
function my_complex_query( $refresh = false ) {
$last_changed = wp_cache_get_last_changed( 'my_group_my_post_type' );
$cache_key = 'my_result'.md5( $param1 . $param2 ).$last_changed;
if ( $refresh || false === ( $results = wp_cache_get( $cache_key ) ) ) {
$query_args = array(); // define my query args using $param1 and $param2
$results = new WP_Query( $query_args );
wp_cache_set( $cache_key, $results, 'my_group', HOUR_IN_SECONDS );
}
return $results;
}
/**
* Hook on save_post to burn a new 'last_changed' timestamp
*/
function my_theme_flush_cache( $post_id ) {
wp_cache_set( 'last_changed', microtime(), 'my_group_'.get_post_type( $post_id ) );
}
add_action( 'save_post', 'my_theme_flush_cache' );
Owner

luistinygod commented Mar 20, 2017

More about this gist on my blog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment