Search code examples
wordpresspostprivate

WordPress displays private posts to logged-in users -- how to turn this functionality off?


On a new WordPress 2.8 installation, I have some posts assigned to category Foo that were previously public but have since been made private. When I am logged into WordPress (as the admin) and happen to also be browsing the Foo category page in a different tab in the same browser, I can see the private posts on the category page, with the entry titles prefixed by the word "PRIVATE: ".

Now, nothing is "broken" about this -- the posts are correctly hidden from non-logged-in users. But I don't want logged-in users to see the private posts on the live site, because frankly it's just annoying, not helpful.

What should I do to the WP Loop on the category archive page or to the functions file to turn off this unwanted ability to see private posts on the site?


Solution

  • The hack way to do what you want is to put this line of code at the top of your loop (after the the_post() part:

    if( get_post_status()=='private' ) continue;
    

    This is the hack way because your WordPress is still loading that post from the database and factoring it in to post counts, etc, but skipping it when going to display it. If you searched for a phrase that was only in private posts, you would get a blank page without any error, for example.

    The correct way to do this is to add a filter that modifies the SQL used to generate the list of posts. The tricky part is to not filter it if you're in the admin section, otherwise you'll never see your private posts again. The best place for this filter is in your theme's functions.php file. Here's what you should put in there:

    add_filter('posts_where', 'no_privates');
    function no_privates($where) {
        if( is_admin() ) return $where;
    
        global $wpdb;
        return " $where AND {$wpdb->posts}.post_status != 'private' ";
    }