Query Custom posts of same taxonomy as the post itself

I have 2 custom post types: “Services” and “Works” and they both have a same taxonomy ‘Genre’. Now the taxonomy ‘Genre’ has as term called ‘novice’. 5 Recent posts under “Works” which has the term ‘novice’ (under taxonomy ‘Genre’) has to be queried on the post pages of “Services” which has the term ‘novice’ (under taxonomy ‘Genre’). There will be 50 terms under the taxonomy.

Related posts

Leave a Reply

1 comment

  1. Assuming you want it for all the terms in the ‘Genre’ taxonomy. In the loop on the single Service post page, put this code:

    <?php
    $the_terms = get_the_terms( get_the_ID, 'genre' );
    if(isset($the_terms) && !empty($the_terms)){
        foreach($the_terms as $the_term){
            $the_terms_slugs[] = $the_term->slug;
        }
    }
    
    $works = get_posts(array(
                                    'post_type' => 'works',
                                    'posts_per_page' => 5,
                                    'tax_query' => array(array(
                                        'taxonomy' => 'genre',
                                        'field' => 'slug',
                            'terms' => $the_terms_slugs
                                    )));
    
    //This will print the works which have the same genre as the current post
    print_r($works_query);
    ?>
    

    If you want it only for ‘novice’, let me know and I’ll modify the code.