How do I check if a posts status is set to draft or pending?

I would like to check a posts status, in particular I want to know if a post is set to draft or is privately published.

I have the following code:

   if ('draft' !=  get_post_status() || is_user_logged_in()) {
        $this->render();
    }
    else {
        wp_redirect( site_url('404') );
        exit;
    }

It checks to see if a posts status is not set to draft or it checks if they are logged in and then renders either the post or redirects to the 404 page.

For some reason privately published posts are visible to non logged in users and I am trying to fix this.

2 Answers
2

To check post with post status private, you could run the following:

if (get_post_status() == 'private' && is_user_logged_in()) {
     // it's private and user is logged in, do stuff
} elseif (get_post_status() == 'draft') {
     // it's draft, do stuff
} else {
      // it's something else, do stuff
}

Or, in your current setup, you can simply only display published posts via:

if (get_post_status() == 'publish') {
     // it's published, do stuff
     $this->render();
}

You can learn more about post statuses via the codex page.

Leave a Comment