You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:36:04