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

WordPress中post__not_in参数未按预期生效问题求助

问题分析与修复方案

你的代码核心问题是**post__not_in参数用了固定的文章ID(1014),而不是当前文章的ID**,所以无法排除当前文章。另外还有几个细节需要优化:

  • WordPress中文章ID的规范属性是$post->ID(大写ID),虽然小写$post->id偶尔能生效,但建议遵循官方规范。
  • 直接输出$image[0]只会显示图片URL,需要改成<img>标签才能正常展示图片。
  • 直接遍历$related->posts不是WP查询的标准写法,建议用have_posts()循环,同时记得重置查询避免影响全局变量。

修正后的完整代码:

global $post;
$post_id = $post->ID; // 修正为规范的大写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;
  
$related = new WP_Query(
    array( 
        'category__in'   => $cat_ids,
        'post_type'      => 'post',
        'post__not_in'    => array($post_id), // 替换为当前文章ID,实现排除效果
        'posts_per_page'  => 1, // 数字类型参数无需加引号
     )
);
$mr = "";
$mr .= "<p style='background:#EAEAEA; padding:40px; color:#000;'>";
if ($related->have_posts()) {
    while ($related->have_posts()) {
        $related->the_post();
        $mr .= get_the_title();
        $image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium');
        if ($image) { // 增加判断,避免无缩略图时报错
            $mr .= '<img src="'.$image[0].'" alt="'.get_the_title().'" style="display:block; margin-top:10px; max-width:100%;">';
        }
    }
    wp_reset_postdata(); // 重置查询,恢复全局$post变量的原始状态
}else{
    $mr .= 'No results!';
}
$mr .= "</p>";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:15:04