Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress Transient Caching
<?php
/**
* Setup wp_query arguments for the loop. Cache the results for 4 hours.
*
* @link http://codex.wordpress.org/Transients_API
*/
// Check for transient
if ( false === ( $my_query = get_transient( 'foo_featured_posts' ) ) ) {
// If transient isn't set, execute WP_Query
$my_query = new WP_Query(
array(
'category' => 'featured',
'posts_per_page' => 5
)
);
// Set transient, and expire after 4 hours
set_transient( 'foo_featured_posts', $my_query, 4 * HOUR_IN_SECONDS );
}
/**
* Run the loop.
*
* @link http://codex.wordpress.org/The_Loop
*/
if ( $my_query->have_posts() ) :
while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<!-- Do stuff -->
<?php endwhile; else : ?>
<p>Sorry, no posts found</p>
<?php endif; wp_reset_postdata(); ?>
@espellcaste

This comment has been minimized.

Copy link

@espellcaste espellcaste commented Feb 4, 2016

Hi, have you confirmed or seen any downsides or code break or slowness when you have an object cache such as Redis with this approach?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment