Access trashed WordPress posts on the front-end

I’ve got this script to list all the post titles with permalinks including posts that are in the trash, on the 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>

This works fine. But the problem is if I click on any of the post titles that are in the ‘trash’, I get the 404 page.

Read More

How can I access trashed posts on the front-end? I understand this the default WordPress behaviour, but is there perhaps a function that allows trash posts to be viewed?

Thanks in advance.

Related posts

1 comment

  1. By default, only published posts are displayed by the main query for all users and additional private posts for logged in users. So we can use the pre_get_posts hook to add an additional post status to the main query

    This is totally untested, not sure it will work, but you can try the following

    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') );
        }
    });
    

Comments are closed.