Skip to content

Instantly share code, notes, and snippets.

@greenhornet79
Created February 17, 2017 15:51
Show Gist options
  • Save greenhornet79/b7cc7f389ba6d0539542d5cabd26c502 to your computer and use it in GitHub Desktop.
Save greenhornet79/b7cc7f389ba6d0539542d5cabd26c502 to your computer and use it in GitHub Desktop.
a basic example of using transients to cache a database query in WordPress
<?php
/**
* Caches the query for 15 minutes to a transient
* @param string $color a meta key
* @return array $posts an array of post objects
*/
function caching_query_example_function( $color ) {
$cache_key = 'color-transient-' . $color;
if ( false === ( $posts = get_transient( $cache_key ) ) ) {
$posts = get_posts( array(
'meta_query' => array(
array(
'key' => 'color',
'value' => $color,
'compare' => 'NOT LIKE',
),
),
) );
set_transient( $cache_key, $posts, 900 );
}
return $posts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment