WordPress single-courses.php基于分类法术语展示关联课程问题
解决方案
你原有的查询参数写法有误,get_posts 中筛选分类法需要通过 tax_query 参数定义规则,同时你需要先获取当前单篇课程绑定的 course_category 分类术语ID,再传入查询条件,同时排除当前课程避免重复展示,修改后的完整代码如下:
<?php // 获取当前文章的course_category分类术语ID $current_course_terms = wp_get_post_terms( get_the_ID(), 'course_category', array( 'fields' => 'ids' ) ); // 仅当拿到分类ID时执行查询 if ( ! empty( $current_course_terms ) && ! is_wp_error( $current_course_terms ) ) { $related = get_posts( array( 'post_type' => 'courses', 'posts_per_page' => -1, 'post__not_in' => array( get_the_ID() ), // 排除当前课程 'tax_query' => array( array( 'taxonomy' => 'course_category', 'field' => 'term_id', 'terms' => $current_course_terms ) ) ) ); 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(); } ?>
修改说明
- 先通过
wp_get_post_terms获取当前课程对应的course_category分类ID数组,避免无分类时查询报错 - 新增
tax_query筛选规则,仅查询和当前课程同分类的课程文章 - 新增
post__not_in参数,排除当前正在浏览的课程,避免重复展示 - 把废弃的
numberposts替换为推荐的posts_per_page参数,兼容性更好 - 如果你的课程支持同时绑定多个
course_category分类,且需要关联课程匹配当前课程的所有分类,可以在tax_query的规则中新增'operator' => 'AND'参数即可
内容的提问来源于stack exchange,提问作者Carina
相关产品推荐
相关产品推荐

