Skip to content

Instantly share code, notes, and snippets.

@gregrickaby
Last active January 2, 2019 10:45
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gregrickaby/5677668 to your computer and use it in GitHub Desktop.
Save gregrickaby/5677668 to your computer and use it in GitHub Desktop.
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
Copy link

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