Using WordPress transients for storing query results

While developing a WorPress application you will eventually come across a situation where you need to use a piece of data frequently in your code. For example say, I maintain a visit count for visits by users for every post. This can be done by incrementing meta value of post ‘user_visits’ every time a post is visited. Now I want to show post from last 2 days which has visits more than 1000 on post archive page.
This can be achieved using query

$args = array(
    'post_status' => 'publish',
    'meta_query' => array(
    	'key'     => 'user_visits',
    	'value'   => 1000,
    	'compare' => '>',
    	'type'    => 'NUMERIC',
    ),
    'date_query' => array(
         array(
             'after'     => '2 days ago',  // or '-2 days'
             'inclusive' => true,
         ),
     ),
);
$posts = new WP_Query( $args );

if ( $posts->have_posts() ) {
    echo '
<ul>';
    while( $posts->have_posts() ) {
        echo '
	<li><a href="' . get_permalink() . '">' . the_title( '', '', false ) . '</a></li>
';
    }
    echo '</ul>
';
}

Looks pretty straight forward with the use of meta query and date query, right?
But keep in mind that this query is going to fire every time we load the archive post page. Definitely huge impact on the performance here.

Let’s bring transients into the picture here and modify the above code. Transients in WordPress do have expiration time so we are going to utilize that. Let’s store this query result in transient and set expiration time of 1 hour so that after every on hour it will update the result of the query.

$posts = get_transient( 'top_visited_posts' );

if ( false === $posts ) {
	$args = array(
	    'post_status' => 'publish',
	    'meta_query' => array(
	    	'key'     => 'user_visits',
	    	'value'   => 1000,
	    	'compare' => '>',
	    	'type'    => 'NUMERIC',
	    ),
	    'date_query' => array(
	         array(
	             'after'     => '2 days ago',  // or '-2 days'
	             'inclusive' => true,
	         ),
	     ),
	);
	$posts = new WP_Query( $args );

	set_transient( 'top_visited_posts', $posts, HOUR_IN_SECONDS );
}

if ( $posts->have_posts() ) {
    echo '
<ul>';
    while( $posts->have_posts() ) {
        echo '
	<li><a href="' . get_permalink() . '">' . the_title( '', '', false ) . '</a></li>
';
    }
    echo '</ul>
';
}

Now our code is ready to utilize the power of the transients.
The expensive query will be fired once every hour only.
On top of that transient utilizes the object cache if in place so that site can be benefited that way too.