The other day I realized that I had a lot of posts sitting in draft mode, but I wanted to have a look and see what the Blog loop looked like. Obviously viewing the draft post isn’t a big deal. I began to wonder if it was possible to display draft posts in the blog loop.
I came across the pre_get_posts
filter that accepts $query
. After doing a bit more digging I found that WordPress also has a suppress_filters
that you can read about here.
Essentially what we want to do is leave the query alone if we are on the admin side of the site. We do that by checking if we are in the admin by looking at is_admin()
Next, we check to see if the user is an administrator by calling user_can( wp_get_current_user(), 'administrator' )
. we also want to honor what suppress_filters
is set to and if it is set and set to true we will leave $query
alone.
After all of that, we should now be a logged-in administrator that is viewing the site from the front end. Setting post_status
to 'publish', 'draft'
and finally returning $query
.
Summing it up.
Here is the full code, that you can add to your themes functions.php
function show_draft_posts( $query ) {
if ( is_admin() ) {
return $query;
}
if ( user_can( wp_get_current_user(), 'administrator' ) ) {
if ( array_key_exists( 'suppress_filters', $query->query_vars ) and $query->query_vars['suppress_filters'] ) {
return $query;
}
$query->set( 'post_status', [ 'publish', 'draft' ] );
return $query;
}
}
add_filter( 'pre_get_posts', 'show_draft_posts' );
Looking at your blog loop you should see all published and draft posts.
For an added bonus, I have a small indicator that the post is a draft by adding this snippet by the title.
<?= ( is_user_logged_in() and get_post_status() == "draft" ) ? "<small>~ Draft ~</small>" : "" ?>
I hope the has helped you out in some way. If your anything like me you have plenty of draft blog posts but never enough time to publish them.