Skip to content

Instantly share code, notes, and snippets.

@isotrope
Created May 22, 2014 12:14
Show Gist options
  • Save isotrope/2cfc6ac297d0e43fd148 to your computer and use it in GitHub Desktop.
Save isotrope/2cfc6ac297d0e43fd148 to your computer and use it in GitHub Desktop.
WordPress: Get the X latest posts with the added benefit of using transients to save it from actually running when not necessary.
<?php
/**
*
* Get a potentially cached version of a WP_Query
*
* @param int $how_many Optional. How many posts to return.
* @return WP_Query
*/
function get_transient_query($how_many = 10) {
// Dynamically create the transient name based on number of $how_many
$transient_name = 'transient_query_' . $how_many;
// Try to get the transient
$transient_query = get_transient($transient_name);
// Aw shucks, the transient isn't there or is expired
if (false == $transient_query) {
// Prep our $args
$args = array(
post_status => 'published',
posts_per_page => $how_many,
);
// Instantiate a new WP_Query
$transient_query = new WP_Query($args);
// save it as a new transient / update the existing, expired transient
set_transient($transient_name, $transient_query, 1 * HOUR_IN_SECONDS);
}
/*
* either it was already stored as a transient and we're simplyu returning it
* or we're returning a freshly stored copy of the query
*/
return $transient_query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment