|
<?php |
|
|
|
/** |
|
* Return related post results by Taxonomy |
|
* @since 0.1.0 |
|
* @param string $taxonomy Taxonomy slug, example: 'category', 'post_tag', 'taxonomy_slug' |
|
* @param int $id Post ID |
|
* @return object Related Query |
|
*/ |
|
function wds_get_related( $taxonomy = 'post_tag', $id = 0 ) { |
|
|
|
// Check if an ID was given to check against vs current loop ID |
|
// 0 is effectively false, so will default to loop's ID |
|
$id = $id ? absint( $id ) : get_the_ID(); |
|
// Create a transient key out of our taxonomy slug and post ID |
|
$trans_id = 'wds_related_'. $taxonomy .'-'. $id; |
|
|
|
// Check if a transient refresh is requested |
|
// (via a query arg added to url, '?delete-trans=true' ) |
|
$reset = isset( $_GET['delete-trans'] ) && $_GET['delete-trans'] == true; |
|
|
|
// Check if we have a related query saved to a transient |
|
if ( false !== ( $trans = get_transient( $trans_id ) ) && ! $reset ) |
|
// if so, and we don't want to refresh the transient, return it |
|
return $trans; |
|
|
|
// Ok, get our taxomony terms on the post |
|
$terms = get_the_terms( $id, $taxonomy ); |
|
|
|
// If we don't have any terms, return false |
|
if ( ! isset( $terms[0]->slug ) ) |
|
return false; |
|
|
|
// Get our related query |
|
$related = new WP_Query( array( |
|
'posts_per_page' => 8, |
|
// exclude our current post |
|
'post__not_in' => array( $id ), |
|
'tax_query' => array( |
|
array( |
|
'taxonomy' => $taxonomy, |
|
'field' => 'slug', |
|
// More restrictive |
|
// 'terms' => wp_list_pluck( $terms, 'slug' ), |
|
/** |
|
* wp_list_pluck serves the same purpose as: |
|
* |
|
* $categories = get_the_category( get_the_ID() ); |
|
* $category_ids = array(); |
|
* foreach( $categories as $single_category ) $category_ids[] = $single_category->term_id; |
|
*/ |
|
|
|
'terms' => $terms[0]->slug, |
|
), |
|
) |
|
) ); |
|
if ( $related->have_posts() ) { |
|
// if we have posts, save the query to a transient |
|
set_transient( $trans_id, $related, 60*60*24 /* a day */ ); |
|
// & return the query |
|
return $related; |
|
} |
|
|
|
// Nothing to see here :( |
|
return false; |
|
} |