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.
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; ?>
5 Responses
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.
Thanks JamieO, I’m glad you enjoyed this recipe
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: