Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cache a slow WP_Query in WordPress
<?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