Last active
April 30, 2020 04:57
-
-
Save luistinygod/af876d9c64c3704dc4031f2a65074ca7 to your computer and use it in GitHub Desktop.
WordPress: Cache patterns for complex queries
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 | |
/** | |
* 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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
learn from here -> https://pressjitsu.com/blog/dont-cache-wp_query/