|
<?php |
|
|
|
/** |
|
* Get related posts. |
|
* |
|
* @param array $args WP_Query arguments. |
|
* @return object The related posts object. |
|
* @author Greg Rickaby |
|
*/ |
|
function wds_client_get_related_posts( $args = array() ) { |
|
|
|
// Set transient key. |
|
$transient_key = 'wds_client_related_posts_' . get_the_ID(); |
|
|
|
// Attempt to fetch from cache. |
|
$related_posts = get_transient( $transient_key ); |
|
|
|
// If a transient isn't available, run WP_Query... |
|
if ( false === ( $related_posts ) ) { |
|
|
|
// The default related term type. |
|
$term_type = 'tag'; |
|
|
|
// Attempt to get the category. |
|
$term_ids = wp_get_object_terms( get_the_ID(), 'post_tag', array( 'fields' => 'ids' ) ); |
|
|
|
// Fallback to category if no tag is present. |
|
if ( empty( $term_ids ) ) { |
|
$term_type = 'category'; |
|
$term_ids = wp_get_object_terms( get_the_ID(), 'category', array( 'fields' => 'ids' ) ); |
|
} |
|
|
|
// Setup default WP_Query args. |
|
$defaults = array( |
|
"{$term_type}__in" => $term_ids, |
|
'ignore_sticky_posts' => 1, |
|
'no_found_rows' => true, |
|
'orderby' => 'date', |
|
'order' => 'DESC', |
|
'posts_per_page' => 3, |
|
'post__not_in' => array( get_the_ID() ), |
|
'update_post_meta_cache' => false, |
|
'update_post_term_cache' => false, |
|
); |
|
|
|
// Parse arguments. |
|
$args = wp_parse_args( $args, $defaults ); |
|
|
|
// Run the query! |
|
$related_posts = new WP_Query( $args ); |
|
|
|
// Finally, story the data for 24 hours. |
|
set_transient( $transient_key, $related_posts, 24 * HOUR_IN_SECONDS ); |
|
} |
|
|
|
return $related_posts; |
|
} |