Add caching to your plugin


Sooner or later, we all write something that could make use of some caching.  I’ve seen several plugins store cache data using the options API — though this will work, it’s probably not the right place to do this.  Instead, you can easily use the WordPress transient API.  Unlike the options API, the Transients API gives you the option of an expiration.  Perfect for caching a query that needs updating, but doesn’t need run every time your code runs.  Here’s how it works:

function hwp_cached_query() {

	if ( false === ( $hwp_query_results = get_transient( 'hwp_query_results' ) ) ) {
		$hwp_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
		set_transient( 'hwp_query_results', $hwp_query_results, 60*60*24 );
	}

	while ( $hwp_query_results->have_posts() ) : $hwp_query_results->the_post();
		echo '
<ul>
	<li>'; the_title(); echo '</li>
</ul>
';
	endwhile;

	// Reset Post Data
	wp_reset_postdata();

Quick breakdown:

	if ( false === ( $hwp_query_results = get_transient( 'hwp_query_results' ) ) ) {

Here we check to see if the transient entry exists.

		$hwp_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
		set_transient( 'hwp_query_results', $hwp_query_results, 60*60*24 );

If our cached data doesn’t exist, we’ll run our query and cache it. In this case, we’re calling our cached entry ‘hwp_query_results’, using the $hwp_query_results variable, and setting the expiration for 24 hours.

One thought on “Add caching to your plugin

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>