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

WordPress相关分类函数未筛选单篇文章所属分类问题排查

修正函数以仅拉取当前文章所属分类的相关文章

原函数存在几处逻辑错误,导致查询行为不符合预期,以下是修正后的完整代码:

function example_cats_related_post() {
    $post_id = get_the_ID();
    $cat_ids = array();
    $categories = get_the_category( $post_id );

    // 修正条件:仅在分类获取成功且不为空时执行
    if( !empty($categories) && !is_wp_error($categories) ):
        foreach ($categories as $category):
            array_push($cat_ids, $category->term_id);
        endforeach;
    endif;

    // 获取当前文章的正确类型
    $current_post_type = get_post_type($post_id);
    $query_args = array( 
        'category__in'     => $cat_ids,
        'post_type'        => $current_post_type,
        'post__not_in'     => array($post_id),
        'posts_per_page'   => 3,
        'orderby'          => 'date',
        'order'            => 'DESC'
     );

    $related_cats_post = new WP_Query( $query_args );

    if($related_cats_post->have_posts()):
         while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>
            <ul>
                <li>
                    
                    <?php the_post_thumbnail(); ?>
                    <div class="postCont">
                    <div class="catTime">
                        <?php $categories = get_the_category();
                            if ( ! empty( $categories ) ) {
                                echo esc_html( $categories[0]->name );
                        } ?><span>|</span>
                         <?php echo get_the_date(); ?>
                    </div><br>
                        <div class="catTitle">
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                        </a></div><br>
                    <?php the_excerpt(); ?>
                    </div>
                </li>
            </ul>
        <?php endwhile;

        // 恢复原始文章数据
        wp_reset_postdata();
     endif;
}

关键修正点说明:

  • 条件判断修正:原代码中is_wp_error($categories)逻辑颠倒,改为!is_wp_error($categories),确保只有分类获取成功时才收集分类ID。
  • 文章类型参数修正:原代码错误地用get_the_category($categories)获取文章类型,改为get_post_type($post_id)来获取当前文章的正确类型(如post),保证查询仅针对同类型文章。
  • 参数规范优化:将posts_per_page的字符串值改为数字类型,同时添加排序参数让相关文章按最新日期排列。

可选:仅拉取当前文章的主分类相关文章

如果文章有多个分类,希望只拉取编辑页设置的「主要分类」相关文章,可修改分类ID收集逻辑:

// 替换原分类ID收集代码块
if( !empty($categories) && !is_wp_error($categories) ):
    // WordPress默认将主分类放在分类数组的第一位
    $cat_ids = array($categories[0]->term_id);
endif;

内容的提问来源于stack exchange,提问作者KujoCode

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:45:21