Post Pic

WordPress tip: Speed up your blog by caching 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

Jan 25 2012 09:45

Very nice use of WordPress Transients API. Thanks for the tip.

Jan 26 2012 17:56

like the use of transient. i think one improvement might be to flush the transients automatically on creation/editing of new posts.

Jan 26 2012 20:45

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()?

Jan 27 2012 09:05

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.

Jan 27 2012 12:44

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');

Jan 28 2012 03:04

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.

Feb 04 2012 09:14

Thanks for posting this recipe sir, anyway what is transient?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required