Skip to content

Instantly share code, notes, and snippets.

@luistinygod
Last active April 30, 2020 04:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luistinygod/af876d9c64c3704dc4031f2a65074ca7 to your computer and use it in GitHub Desktop.
Save luistinygod/af876d9c64c3704dc4031f2a65074ca7 to your computer and use it in GitHub Desktop.
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' );
@luistinygod
Copy link
Author

More about this gist on my blog

@waqasy
Copy link

waqasy commented Jun 1, 2018

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