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>';
        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.

  • Have you taken a look at the "posts2posts" plugin by scribu?
    – kaiser
    Feb 6, 2013 at 21:45

1 Answer 1


You can use Wordpress's tax_query arg when fetching posts to achieve what you're trying to do, this is also easily extendable with more than one taxonomy.

$query = array(
    'post_type' => $YOUR_POST_TYPE,
    'posts_per_page' => -1 // get all
    'tax_query' => array(
        'relation' => 'OR'

$query['tax_query'][] = array(
    'taxonomy' => 'YOUR_TAXONOMY',
    'terms' => $ARRAY_WITH_TERMS,
    'field' => 'ID',
    'operator' => 'IN'

$query['tax_query'][] = array(
    'taxonomy' => 'YOUR_TAXONOMY_2',
    'terms' => $ARRAY_WITH_TERMS_2,
    'field' => 'ID',
    'operator' => 'IN'

$posts = query_posts( $query );

Might this be what you're looking for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.