Skip to content

Instantly share code, notes, and snippets.

@mjangda
Created September 29, 2011 04:42
Show Gist options
  • Save mjangda/1249989 to your computer and use it in GitHub Desktop.
Save mjangda/1249989 to your computer and use it in GitHub Desktop.
Example of queries with and without caching
<?php
// == Without caching
$args = array( 'orderby' => 'comment_count', 'posts_per_page' => '1', 'ignore_sticky_posts' => 1 );
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
// do stuff
endwhile;
// == With Caching
// First, let's see if we have the data in the cache already
$query = wp_cache_get( 'ordered_comments_query' ); // the cache key is a unique identifier for this data
if( $query == false ) {
// Looks like the cache didn't have our data
// Let's generate the query
$args = array( 'orderby' => 'comment_count', 'posts_per_page' => '1', 'ignore_sticky_posts' => 1 );
$query = new WP_Query( $args );
// Now, let's save the data to the cache
// In this case, we're telling the cache to expire the data after 300 seconds
wp_cache_set( 'ordered_comments_query', $query, '', 300 ); // the third parameter is $group, which can be useful if you're looking to group related cached values together
}
// Once we're here, the $query var will be set either form the cache or from manually generating the WP_Query object
while ( $query->have_posts() ) : $query->the_post();
// do stuff
endwhile;
// The benefit here of doing things this way is that for particularly complex queries or operations, we avoid having to do them for every user on every page load because the data has been fetched previously.
// Ideally, you wouldn't pass an expires value and do smart cache invalidation instead. For example, hook into save_post and call wp_cache_delete with the cache key(s). That way you ensure that you only really need to regenerate the cache data when it's changed.
// There are certain cases where you would use unique cache keys, for example, say you have a gallery slider on different category pages and you're caching the results of the query used to generate it. If you used the same key across the board, you'd end up with the same data everywhere. Instead, you can suffix the cache key with something like the category id to make sure you have unique key for each cached data set. In particularly complex cases, you can use an md5 value of the query args as the cache key.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment