How do I display content to users who are not logged in instead of 404 on Private custom posts?

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.";
}

Read More

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?

Related posts

Leave a Reply

1 comment

  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
    }