I'm trying to write a function that will grab all related posts according to the term of a taxonomy. I'm having trouble though trying to query multiple terms.
The way I am doing it right now is using whatever the first term is to query related posts. Any idea how to check if it is multiples?
function related_posts($related_type, $related_tax) {
global $wpdb, $post;
// Get The Related Term
$terms = array();
foreach(wp_get_object_terms($post->ID, $related_tax) as $term){
$terms[] = $term->slug;
};
// Grab The First Term From The Array
$related_term = array_shift(array_values($terms));
// Query The Related Posts
$related_posts = $wpdb->get_results(
"
SELECT *
FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->posts.post_type = '$related_type'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = '$related_tax'
AND $wpdb->terms.slug = '$related_term'
AND $wpdb->posts.ID <> $post->ID
ORDER BY $wpdb->posts.post_date DESC
"
);
if($related_posts) {
echo '<ul>';
foreach ($related_posts as $post):setup_postdata($post);
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endforeach;
echo '</ul>';
} else {
echo 'No related posts found';
}
}
I would like something like: if this term OR this term OR this term THEN display all related posts.
I had previously used $wpdb->terms.slug IN ('$terms') but this would only show related posts with that exact match.