-
-
Save jlapitan/f06b82febd7e3311632836b94514d895 to your computer and use it in GitHub Desktop.
Cache a slow WP_Query in WordPress
This file contains hidden or 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 | |
/** | |
* Function that gets recent posts | |
*/ | |
function get_recent_posts() { | |
//No cache | |
if(!wp_cache_get('my_complex_query_result')) { | |
//This is the super slow query. | |
$query = new WP_Query(array( | |
'posts_per_page' => 3 | |
)); | |
//Grab the ID:s so we can make a much more lightweight query later | |
$post_ids = wp_list_pluck( $query->posts, 'ID' ); | |
//Cache it! | |
wp_cache_set('my_complex_query_result', $post_ids); | |
$posts = $query->posts; | |
} | |
//Cache! | |
else { | |
//Lightweight query using post__in | |
$query = new WP_Query(array( | |
'post__in' => wp_cache_get('my_complex_query_result'), | |
'posts_per_page' => -1 | |
)); | |
$posts = $query->posts; | |
} | |
return $posts; | |
} | |
/** | |
* Invalidation function. When posts get saved or published we delete the saved post list | |
* because it may have changed. | |
*/ | |
add_action('save_post', function() { | |
wp_cache_delete('my_complex_query_result'); | |
}); | |
/** | |
* Run this function anywhere. First run will do the heavy WP_Query and | |
* the others will do a fast one | |
*/ | |
get_recent_posts(); // 8 query overhead | |
get_recent_posts(); //Only 1 query overhead | |
get_recent_posts(); //Only 1 query overhead |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment