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

如何让WordPress的get_post()函数不返回已移入回收站的文章?

解决WordPress get_post()获取未移入回收站文章的问题

嗨,这个问题我之前也碰到过!核心原因是get_post()函数默认的post_status参数是any——也就是说,它会获取所有状态的文章,包括已经被移到回收站(状态为trash)的内容,所以即使你把文章丢去回收站,它还是会被捞出来展示。

两种高效的解决方法:

方法一:在get_post()中直接指定有效状态

调用get_post()的时候,传入参数数组,明确限定只获取已发布状态的文章(或者你需要的其他非回收站状态),这样回收站里的内容会直接被过滤掉:

// 假设你从自定义器拿到的特色文章ID存在这个变量里
$featured_post_id = get_theme_mod( 'your_featured_post_setting' );

// 只获取已发布的文章,自动排除回收站、草稿等状态
$featured_post = get_post( array(
    'p'           => $featured_post_id,
    'post_status' => 'publish'
) );

// 只有拿到有效文章时才渲染展示
if ( $featured_post ) {
    // 这里写你的特色文章展示代码
    echo '<div class="featured-post-block">';
    echo '<h3>' . esc_html( get_the_title( $featured_post ) ) . '</h3>';
    echo '<div class="excerpt">' . wp_trim_words( get_the_content( $featured_post ), 20 ) . '</div>';
    echo '</div>';
}

如果你的场景需要包含草稿、私有文章这类非回收站状态,可以把post_status改成数组:

'post_status' => array( 'publish', 'draft', 'private' )

方法二:获取文章后检查状态(适合快速修改)

如果你不想改动原有的get_post()调用方式,也可以在拿到文章对象后,额外判断它的状态是否为回收站:

$featured_post = get_post( $featured_post_id );

// 确保文章存在,且状态不是回收站
if ( $featured_post && $featured_post->post_status !== 'trash' ) {
    // 执行展示逻辑
}

为什么永久删除后就不展示了?

因为永久删除文章后,数据库里的这条记录被彻底移除了,get_post()根据ID找不到对应的内容,会返回false,所以你的展示逻辑自然不会执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:35:52