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

WordPress自定义分类相关文章代码需排除草稿帖问题

解决相关文章显示草稿的问题

嘿,我完全懂这种困扰——草稿文章混进公开的相关推荐里确实不符合预期!问题的核心是你的查询没有明确指定只拉取已发布的文章,WordPress的默认查询会包含所有状态的内容(包括草稿、私密文章等)。

你只需要在相关文章的查询参数里添加post_status字段,指定为'publish'就能过滤掉草稿了。下面是调整后的完整代码片段:

<div class="relatedposts">
<?php
// 获取当前文章的分类和标签
$categories = get_the_category($post->ID);
$tags = get_the_tags($post->ID);

if ($categories || $tags) {
    $category_ids = array();
    if($categories) {
        foreach($categories as $individual_category) {
            $category_ids[] = $individual_category->term_id;
        }
    }

    $tag_ids = array();
    if($tags) {
        foreach($tags as $individual_tag) {
            $tag_ids[] = $individual_tag->term_id;
        }
    }

    // 构建查询参数,添加发布状态过滤
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish', // 关键:只拉取已发布的文章
        'posts_per_page' => 4,
        'post__not_in' => array($post->ID),
        'orderby' => 'rand',
        'tax_query' => array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $category_ids
            ),
            array(
                'taxonomy' => 'post_tag',
                'field' => 'id',
                'terms' => $tag_ids
            )
        )
    );

    $related_query = new WP_Query($args);

    if($related_query->have_posts()) {
        echo '<h3>相关文章</h3>';
        echo '<ul>';
        while($related_query->have_posts()) {
            $related_query->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        echo '</ul>';
        wp_reset_postdata();
    }
}
?>
</div>

关键说明:

  • 添加的'post_status' => 'publish'参数是核心,它会告诉WordPress只返回已经发布的公开文章,彻底排除草稿、私密、待审核等状态的内容。
  • 如果你之后需要包含其他特殊状态的文章(比如给特定用户看的私密文章),可以把这个值改成数组形式,比如'post_status' => array('publish', 'private'),但当前场景下publish就足够解决问题了。

这样修改后,你的相关文章模块就只会显示正式发布的内容啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:07:44