Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Created March 23, 2017 19:34
Show Gist options
  • Save kellenmace/0d2bdf9587ae7818be353b7fb9fbeed4 to your computer and use it in GitHub Desktop.
Save kellenmace/0d2bdf9587ae7818be353b7fb9fbeed4 to your computer and use it in GitHub Desktop.
Caching WP_Query posts
/**
* Get an array of all portfolio posts.
*
* @since 8.0.0
* @author Kellen Mace
* @return array $portfolio_posts Array of portfolio post WP_Post objects.
*/
function wds_eight_get_portfolio_posts() {
$portfolio_posts = get_transient( 'wds_portfolio_posts' );
// If value stored in transient is valid and we're not busting the cache, use it.
if ( is_array( $portfolio_posts ) && ! isset( $_GET['delete-transients'] ) ) {
return $portfolio_posts;
}
$portfolio_posts = array();
// Run a new query to fetch the data.
$portfolio_query = new WP_Query( array(
'posts_per_page' => 500,
'post_type' => 'portfolio',
//'fields' => 'ids', // Use this if you only need post IDs.
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
) );
if ( $portfolio_query->have_posts() ) {
$portfolio_posts = $portfolio_query->get_posts();
}
set_transient( 'wds_portfolio_posts', $portfolio_posts, WEEK_IN_SECONDS );
return $portfolio_posts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment