Restrict Pages in WordPress to Require a Login

login_lock.jpgThis week, we were finishing up implementing a custom theme on a client site and they requested that we build some kind of interaction where some of the pages were restricted to registered subscribers. At first, we thought about implementing third party plugins, but the solution was actually quite simple.

First, we copied the page template to a new file (any name is fine, just maintain the php extension). At the top of the page, be sure to comment on the page so that you can see it in the template editor by name:

<?php /* Template Name: Subscribers Only */ ?>

Next, look for the line in your page’s code that displays the content. It should look like this:

<?php the_content(); ?>

Now, you’ll need to wrap some code around that line:

<?php global $user_ID;
get_currentuserinfo(); ?>
<?php if($user_ID) { ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php } else { ?>
<h2>Subscriber Only</h2>
<p>We're sorry, the content you are trying to reach is restricted to subscribers only.</p>
<?php } ?>

The code starts by checking the session to see if the user is logged into your WordPress site. If they are logged in, the content is displayed. If they are not logged in, the message states that you are trying to reach restricted content.

In order to utilize the page, you’ll need to select the Subscribers Only page template in the advanced section of your page’s options (on the sidebar). That will restrict the page to readers who are logged in.

If you’d like to get really fancy, you can add a login and logout method to your sidebar as well:

<?php global $user_ID;
get_currentuserinfo(); ?>
<?php if($user_ID) { ?>
<li><a href="<?php echo wp_logout_url(); ?>">Logout</a></li>
<?php } else { ?>
<li><a href="<?php get_settings('home'); ?>/wp-login.php">Customer Login</a></li>
<?php } ?>

You might also find these posts interesting: