WordPress Transients Tutorial, Part 2
This file contains 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 | |
/** | |
* Get Books posts. | |
* | |
* This is from a tutorial found here: | |
* @link https://johnregan3.wordpress.com/how-to-improve-wordpress-load-times-using-transients | |
* | |
* @since 1.0.0 | |
* | |
* @param array $genre_array An array of genre slugs. | |
* @param array $publisher_array An array of publisher slugs. | |
* | |
* @return array Array of books, else an empty array. | |
*/ | |
function jr3_get_books( $genre_array, $publisher_array ) { | |
/* | |
* For the sake of this tutorial, we'll assume | |
* $genre_array and $publisher_array are valid arrays. | |
*/ | |
$wp_query_args = array( | |
'post_type' => 'book', | |
'tax_query' => array( | |
'relation' => 'OR', | |
array( | |
'taxonomy' => 'genre', | |
'field' => 'slug', | |
'terms' => $genre_array, | |
), | |
array( | |
'taxonomy' => 'publisher', | |
'field' => 'slug', | |
'terms' => $publisher_array, | |
), | |
), | |
); | |
// Generate the transient name. | |
$transient_name = 'jr3_' . md5( maybe_serialize( $wp_query_args ) ); | |
$books = get_transient( $transient_name ); | |
if ( ( false === $books ) || ( ! is_array( $books ) ) ) { | |
$books = array(); | |
// Run the Query. | |
$query = new WP_Query( $wp_query_args ); | |
if ( is_array( $query->posts ) ) { | |
// Rename for output. | |
$books = $query->posts; | |
// Set our transient using our generated name. | |
set_transient( $transient_name, $books, HOUR_IN_SECONDS ); | |
} | |
} | |
return $books; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment