WordPress show related posts based on taxonomy term

Below I have this code in single-courses.php which is currently displaying all the the courses. The goal is to show only related courses based on that courses' taxonomy term (category). Help please.

<?php
                                                
    $related = get_posts( array( 
        'taxonomy' => 'course_category',
        'post_type' => 'courses',
        'numberposts'  => -1 
    ) 
);

if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>

    <div class="row next-chapter-list" onclick="location.href='<?php the_permalink();?>';">
        <div class="col-md-10 col-9 valign text-left">
            <?php the_title(); ?>
        </div>
        <div class="col-md-2 col-3 valign text-right">
            <i class="bi bi-play-fill"></i>
        </div>
    </div>

<?php }
wp_reset_postdata(); ?>

Comments


  • traveler

    i found a solution literally after i posted this question, sorry- but this is what worked for me.

    <?php
            //get the post's venues
        $custom_terms = wp_get_post_terms($post->ID, 'course_category');
    
        if( $custom_terms ){
    
            // going to hold our tax_query params
            $tax_query = array();
    
            // add the relation parameter (not sure if it causes trouble if only 1 term so what the heck)
            if( count( $custom_terms > 1 ) )
                $tax_query['relation'] = 'OR' ;
    
            // loop through venus and build a tax query
            foreach( $custom_terms as $custom_term ) {
    
                $tax_query[] = array(
                    'taxonomy' => 'course_category',
                    'field' => 'slug',
                    'terms' => $custom_term->slug,
                );
    
            }
    
            // put all the WP_Query args together
            $args = array( 'post_type' => 'courses',
                            'posts_per_page' => 5,
                            'tax_query' => $tax_query );
    
            // finally run the query
            $loop = new WP_Query($args);
    
            if( $loop->have_posts() ) {
    
                while( $loop->have_posts() ) : $loop->the_post(); ?>
    
                <div class="row next-chapter-list" onclick="location.href='<?php the_permalink();?>';">
            <div class="col-md-10 col-9 valign text-left">
                <?php the_title(); ?>
            </div>
            <div class="col-md-2 col-3 valign text-right">
                <i class="bi bi-play-fill"></i>
            </div>
        </div>     
                <?php 
    
                endwhile;
    
            }
    
            wp_reset_query();
    
        }?>
    

Add Comment