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; ?>

2 Responses

Nov 12 2011 21:29

that snippet doesn’t work!
You should use the post_status property:
post_status == “private” ){ … } ?>

Jan 12 2012 14:00

Hi.

Where should I place this code? Which file? Where is “my current WordPress loop”?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required