Quantcast
Viewing all articles
Browse latest Browse all 4

Speed Up WordPress – Cache Custom Queries

Pretty simple concept.  Just like caching images, pages and whatever else on the front end of your site, you can also cache pieces of your database queries for faster application performance.  We’ll be using the built in WordPress Transients API to accomplish this with just a few lines of code.  So here is the concept, let’s say you have a custom query to list posts on a blog page.  Typically you’d use the loop like so:

$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC'
);

$query = new WP_Query( $args );
if  ($query->have_posts() : while ($query->have_posts(): $query->the_post();
    //Display your data
endwhile; endif;

You know the drill.  So why not “save” this query for later use, say if the user browses to another page, then comes back to this page.  No need to “re-submit” the query to the database because you can just store it in the site transients.  Using the example above, here is how you would go about that:

// See if we have the special query saved
if ( false === ( $my_special_query = get_transient( 'name_the_transient' ) ) ) {
    // Nope, so regenerate the data and save it
    $my_special_query = new WP_Query( $args );
    set_transient( 'name_the_transient', $my_special_query );
}

// Now go ahead and set your special query for use in the loop from earlier
$query = $my_special_query;

Pretty straightforward stuff and it will take a lot of load off your database. A lot of folks focus so much on gzip compression, minifying your javascript, etc… and there are plenty of performance gains you can implement server-side as well. Hope you can put it to use.


Viewing all articles
Browse latest Browse all 4

Trending Articles