How to: Only display private posts to logged users in the loop

If you want to be able to display private posts only to registered users within the loop, I’m pretty sure you’ll enjoy this recipe: I’m explaining how to do it, with a code exemple you can re-use on your blog.

To achieve this recipe, you'll have to define a custom field named private, with true as a value, to each private post will have. In our WordPress loop, we'll check if the post have a private custom field, and if true is its value. If yes, we'll check out if the user is logged in. If he is, the post will be displayed. Otherwise, it will not.

Replace your current WordPress loop with that one:

<?php
if (have_posts()) :
     while (have_posts()) : the_post();
     $private = get_post_custom_values("private");
         if (  isset($private[0]) && $private == "true"  ) {
 	     if (is_user_logged_in()) {
	     	    // Display private post to logged user
	     }
	 } else {
	     //Display public post to everyone
         }
     endwhile;
endif; ?>

4 Responses

Nov 10 2008 18:51

Great tip. Make sure you apply this logic to any loops that retrieve posts, search results, rss feeds, etc to ensure that your private content stays private.

Nov 10 2008 19:19

Thanks JamieO, I’m glad you enjoyed this recipe :)

Dec 18 2008 22:16

Am I missing something? Why is this needed, since only those logged into the WP admin can view posts marked Private (using the Private setting in the Write panel)? There is no need for a custom value and extra logic..

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required