Need a simple solution for a “members only” WordPress page? “But password-protecting a single page is part of WP core!” you say — and you’re right, except if you want to display additional content not part of the protected post. Read on for how to customize a post template to protect category loops and other page elements.
When creating content, you can hide it behind a simple password on the right sidebar under “Visibility” — choose “Password protected”, and enter your password. As long as you don’t need the precision, this avoids the complication of multiple user accounts and role/permission integration.
However, if you are using a custom template on a “category” page (i.e. you have an additional query loop for other content) like, say, a products page for a store, or member database then you’ll need to wrap the additional content in a password check.
Fortunately, Codex to the rescue — all you need is the simple function call post_password_required()
. Wrap an if-else
clause around the additional queries, and you’re done!
Example:
<?php get_header(); ?> <div> <div id=”content” role=”main”> <?php //initial loop for calling page if ( have_posts() ) while ( have_posts() ) : the_post(); … stuff … ?> <div id=”post-<?php the_ID(); ?>” <?php post_class(); ?>> <div> … </div><!– .entry-content –> </div><!– #post-## –> <?php endwhile;//—- end post loop //only do the following if the calling page is allowed if(!post_password_required()): ?> <div> <?php query_posts( ‘post_type=abt_member’); // calls in all posts of the custom type ?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div <?php post_class(); ?>> … stuff … </div><!– #products –> <?php endwhile; ?> </div> <?php endif; //—- !post_password_required() ?> </div><!– #content –> <?php get_sidebar( ‘store’ ); ?> </div><!– #container –> <?php get_footer(); ?>
Strangely, WordPress doesn’t allow you to “log out” of password-protected pages, and it doesn’t seem like deleting cookies makes a difference. Of course, someone made a plugin that’ll take care of that — install the plugin, then add the following to your template:
do_action(‘posts_logout_link’, ‘TEXT ON THE LOGOUT LINK’);
Further reading – Digging into WordPress – password protect more than the content.