2

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.

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.

User_FTW
  • 504
  • 1
  • 16
  • 44
  • I'm curious why you want to display trashed posts on the front-end, if you don't mind elaborating on that, thanks. – birgire Jul 21 '15 at 10:09

1 Answers1

4

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') );
    }
});
Pieter Goosen
  • 9,768
  • 5
  • 35
  • 55
  • Thanks @Pieter Goosen. It errors: `Parse error: syntax error, unexpected 'function' (T_FUNCTION)` – User_FTW Jul 21 '15 at 08:56
  • Sorry about that, had a missing comma. Fixed. Please see my updated code – Pieter Goosen Jul 21 '15 at 08:59
  • Wow that works! Honestly I didn't think this was going to even be possible on the front-end. Cheers. Bounty awarded :-) Update: When I attempt to award the bounty, it says "You may award your bounty in 21hrs". I'll come back in 21 hours :-) – User_FTW Jul 21 '15 at 10:17
  • My pleasure. You can even extend that and get the value of `post_status` first with `$status = $q->get( 'post_status' );` and then adding trashed to the result of `$status` and then adding that as value to your `post_status` parameter ;-). Enjoy – Pieter Goosen Jul 21 '15 at 10:20
  • Great. Thank you ;-). Enjoy – Pieter Goosen Jul 22 '15 at 08:20