Created
February 17, 2017 15:51
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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