
Is your theme using custom queries? If yes, you should definitely use WordPress Transients API to cache the queries and consequently speed up your blog. Today’s recipe will show you how to cache any custom queries.

Is your theme using custom queries? If yes, you should definitely use WordPress Transients API to cache the queries and consequently speed up your blog. Today’s recipe will show you how to cache any custom queries.
Nothing hard here: simply paste the following code where you need to execute a custom query to the database. Don't forget to update the query on line 5!
<?php
// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
// It wasn't there, so regenerate the data and save the transient
$special_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
set_transient( 'special_query_results', $special_query_results );
}
// Use the data like you would have normally...
?>
This code is using WordPress Transients API. Click here to view more useful examples of this API!
Credits: WordPress Codex.
7 Responses
Very nice use of WordPress Transients API. Thanks for the tip.
like the use of transient. i think one improvement might be to flush the transients automatically on creation/editing of new posts.
Very nice tip. Definitely adding to my arsenal.
Can you take advantage of this API if you’re using your own SELECT statements and $wpdb->get_results()?
good use of transient. if you also just add the flush () command into the header of your installation it will give it that extra kick when loading the site.
In Case somebody wonders how to clear the transients on Post saving by Custom Post Type:
http://pastebin.com/W4pB4zGz
function antwortzeit_transients() {
if($_POST[post_type] == 'nachrichten') {
delete_transient('nachrichten_start');
}
}
add_action('save_post','antwortzeit_transients');
Only downside to this that I see is that it doesn’t work well with queries where you want a random order because the query just returns the same order from the cache.
Thanks for posting this recipe sir, anyway what is transient?
Trackbacks: