1

I want to display a message like "You must be logged in to view this", with Private custom posts. Theoretically, I want to use something like this:

if (is_user_logged_in()) {
// Page code goes here
}
else {
echo "You must be logged in to view this page.";
}

This code is in the single-custom.php page template.
The true case works just fine. However, if the user is not logged in, instead of seeing "You must be logged in..." I get a 404 instead? What am I doing wrong?

1 Answer 1

1

Are you doing this inside The Loop? I'd try something like this myself:

if ($post->post_status == "private" && !is_user_logged_in()) {
    echo "You must be logged in to view this page.";
} else if( $post->post_status == "private" && is_user_logged_in() ) {
    // Page code goes here
}
5
  • I don't seem to have any custom value "Private" (var_dump(get_post_custom($post->ID))) Commented Feb 9, 2011 at 21:51
  • Sorry about that. Let's try monitoring $post->post_status instead. I've edited my answer.
    – editor
    Commented Feb 9, 2011 at 21:56
  • echo $post->post_status; returns private. So $status = $post->post_status; if ($status == "private" && is_user_logged_in()) { echo "Foo<br /><br />";} else { echo "You must be logged in to view this page."; } I get Foo if I'm logged in and looking at a private custom post, but if I'm not logged in, my single-custom.php isn't loaded but 404.php is instead... (soz, dunno why the backticks aren't working for the code -- its basically as per yours but I changed !== "private" to == "private" Commented Feb 9, 2011 at 22:01
  • Hmm, so it sounds like we can detect if it's private once the content is displayed but by then a 404 is served when not logged in. Seems like the determination of wether the page exists or not might be happening at the rewrite level. If you work with plugins, a technique might be to hook onto the rewrite and do something for private posts that allows them to pass the next hurdle.
    – editor
    Commented Feb 11, 2011 at 0:22
  • 1
    It looks like you're in luck. Check out the code posted as an answer here: wordpress.stackexchange.com/questions/9099/… I bet you can adapt that for your purposes.
    – editor
    Commented Feb 11, 2011 at 0:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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