WordPress Snippets at WPcustoms

improve query with transients saving db requests

Here is an example how to use transients in your WordPress loop for a portfolio post type. The query is processed every page load so this can lead to a massive database request if you have multiple queries on the same page. Transients can save the info and quickly return it. It’s a WordPress built-in method for caching content. Please keep in mind that this gets redundant if you have an optimized caching plugin.


/**
 * Snippet Name: improve query with transients saving db requests
 * Snippet URL: https://wpcustoms.net/snippets/improve-query-with-transients-saving-db-requests/
 */
  // check if we already have some info in our transient
if( false === ( $portfolio_query = get_transient( 'saved_portfolio_query' ) ) ) {

// if nothing is returned run the WP_Query
	$portfolio_query = new WP_Query( array(
		'post_type' => 'portfolio',
		'posts_per_page' => 1,
	) );
	set_transient( 'saved_portfolio_query', $portfolio_query , 60*60*4 );
}

// if( have_posts() ) {  } ... run your loop here



// delete transient info when a post is updated paste into functions.php
function wpc_delete_its_transients() {
	global $post;
	if( $post->post_type == 'portfolio' ) {
		delete_transient( 'saved_portfolio_query' );
	}
}
add_action( 'save_post', 'wpc_delete_its_transients' );