访问 front-end 上已删除的 Wordpress 帖子

Access trashed Wordpress posts on the front-end

我有这个脚本来列出所有 post 带有永久链接的标题,包括 post 垃圾桶中的 front-end:

<ul>
<?php
$myposts = get_posts(array(
    'numberposts' => -1,
    'offset' => 0,
    'category' => $cat_id,
    'post_status' => array('publish','trash')  
    )
);
foreach($myposts as $post) :
setup_postdata($post);
?>

    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
</ul>

这很好用。但问题是,如果我单击 'trash' 中的任何 post 标题,我会看到 404 页面。

如何访问 front-end 上已删除的 post?我理解这是默认的 Wordpress 行为,但是否有允许查看垃圾 posts 的功能?

提前致谢。

默认情况下,主查询仅显示所有用户的已发布 post 和已登录用户的其他私有 post。所以我们可以使用 pre_get_posts 钩子向主查询

添加一个额外的 post 状态

这完全未经测试,不确定是否有效,但您可以尝试以下方法

add_action( 'pre_get_posts', function ( $q )
{
    if (    $q->is_main_query()
         && $q->is_single() // can replace with $q->is_singular()
    ) {
        $q->set( 'post_status', array('publish','trash') );
    }
});