I'm trying to display only those posts which are under the same category of the post which I have clicked as related posts. My custom taxonomy are like this :
Fsc year 1 => Biology => Bio chapter 1 . Now the problem is when I click a post from category bio chapter 1 all the posts in biology and bio chapter 1 display on the page that is the code that I found on google:

    // get the custom post type's taxonomy terms

    $custom_taxterms = wp_get_object_terms( $post->ID, 'category', array('fields' => 'slugs') );

    $args = array(
        'post_type' => 'subject',
        'post_status' => 'publish',
        'posts_per_page' => -1, // you may edit this number
        'orderby' => 'rand',
        'post__not_in' => array ( $post->ID ),
        'tax_query' => array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $custom_taxterms
    $related_items = new WP_Query( $args );
    // loop over query
    if ( $related_items->have_posts() ) : ?>

        <li class="widget widget_categories">
        <h3 class="widget-title">Similar Posts</h3>

        <?php while ( $related_items->have_posts() ) : $related_items->the_post(); ?>

            <li><a href="<?php the_permalink(); ?>"><?php the_excerpt(); ?></a></li>
             <li><a href="<?php the_permalink(); ?>"><?php the_content(); ?></a></li>

        <?php endwhile; ?>


    <?php endif;
    // Reset Post Data

I want to display only bio chapter 1 posts as related post not the parent taxonomy's post in these related posts or if I click post from biology taxonomy only posts from biology show not posts from bio chapter 1 category. Can you please help me how I can do this I'm new to WordPress theme development I'll be very thankful to you.

1 Answer 1


Please follow the below steps.

--- Get the list of the parent term by using the below function get_term_parents_list
for documentation of the function => https://developer.wordpress.org/reference/functions/get_term_parents_list/

--- Get the ids of the posts that belongs to the parent taxonomy. --- Use post__not_in() function in the query to remove the posts belongs to parent taxonomy.

  • Thanks for your help but I have fixed the problem by changing terms value. Jan 18, 2019 at 12:47

Your Answer

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

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