2

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.

6

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.

  • Thanks @Christine - used your answer, adapted it slightly and it works! – Neelam Khan Feb 28 '18 at 14:25
  • Great to hear Neelam; best of luck with your project. – Christine Cooper Feb 28 '18 at 14:39
1

I think the problem is with you logic. || means if any of the condition is satisfied it'll render, specially if the first condition gets satisfied it'll not check the second one anymore. So your code will be like below-

if( !is_user_logged_in() ) {
    return; // or do whatever you want to do if the user isn't logged in.

    // Or these below things 

    // wp_redirect( site_url('404') );
    // exit;
}

if ( 'private' === get_post_status()) {
    // Only render private posts.
    $this->render();
} else {
    wp_redirect( site_url('404') );
    exit;
}

So, what we have done above here is, first we checked if the user is logged in or not. If not logged in we are returning it from there. It's no reaching the next if condition. This way you can prevent non-logged in user from seeing this post. In you code some how the first condition gets satisfied and if isn't checking the next condition. So non-logged in users are able to see your post. Now in second if block we are checking the post status. If the post has private status only then it'll be rendered. Other wise it'll be redirected.

Anyway, some little suggestions, use !== rather than != and === rather than ==. These checks types also and makes it strictly checked. See my code, I used these.

Hope this above helps.

  • Thanks @the_dramatist for your answer, I went with christine's suggestion and adapted it slightly. – Neelam Khan Feb 28 '18 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.