Cache WordPress Query Strings Using Transient API

transients API
In WordPress you can easily create a Query to search all the posts on your blog. All you have to do is use the WordPress WP Query Class and pass in the parameters for the custom query.

The problem with custom queries is that they will normally be returning data is isn't queried by WordPress, this means that it can take longer to return the results. With the results taking longer to come back from the database it can slow down your page loading times.

Luckily WordPress comes with a Transient API where you can cache anything including results from queries.

Below is a WordPress snippet to use next time you need to make a custom query to the WordPress database.

<?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...
?>

Source: Transient API

Advertise here

Comment