Easy Transient integration for WP Query

Last Updated: January 28, 2019

What is Transient API?

The Transients API is very similar to the Options API but with the added feature of an expiration time, which simplifies the process of using the wp_options database table to temporarily store cached information.
Reference: https://codex.wordpress.org/Transients_API

Function

Add this yo your functions.php

// wp query transient
function wp_query_transient($transient_key, $args){
    $query = get_transient( $transient_key );
    if ( false === ( $query ) ) {
		$query = new WP_Query( $args ); 
        set_transient( $transient_key, $query , 12 * HOUR_IN_SECONDS );
    }
    return $query;
}

How to use

$transient_key =  'transient_all_casino_table';
$args = array(
	'post_type'       => 'page',
	'posts_per_page' => -1,
	'meta_key' => 'rating',
	'orderby' => array(
	   'rating' => 'DESC',
	   'title' => 'ASC'
	),
	'meta_query' => array(
		array(
			'key'     => 'review',
			'value'   => 1,
			'compare' => '=',
		),
	),
);
$query = wp_query_transient($transient_key, $args);
if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post(); 
    endwhile; 
    wp_reset_postdata(); 
else :
endif;

How to delete transient?

$transient_key =  'transient_all_casino_table';
delete_transient($transient_key);

Github: https://github.com/renzramos/easy-transient-integration-for-wp-query

Add your feedback or comment below: