WordPress 根据分类术语显示相关帖子

WordPress show related posts based on taxonomy term

下面我在单个 courses.php 中有这段代码,它当前正在显示所有课程。目标是仅显示基于课程分类术语(类别)的相关课程。请帮忙

<?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(); ?>

我在发布这个问题后找到了一个解决方案,抱歉-但这对我有用。

<?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();

    }?>