Last active
November 5, 2023 23:45
-
-
Save khromov/627b54e84614bd4b1082 to your computer and use it in GitHub Desktop.
Cache a slow WP_Query in WordPress
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 | |
/** | |
* 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