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' ); |
This comment has been minimized.
This comment has been minimized.
learn from here -> https://pressjitsu.com/blog/dont-cache-wp_query/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
More about this gist on my blog