WordPress: Create A Page Template That Requires A User To Be Registered and Logged In

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. WordPress does offer Visibility options for pages, but that doesn’t accommodate this scenario.

At first, we thought about implementing third-party plugins, but the solution was simple. We could create a unique template that requires viewers to register and log in to view the page.

WordPress Template: Subscribers Only

First, we copied our client’s page template (page.php) within the child theme. To create a template, you need to add some code to the top of your page:

<?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
$redirect_url = get_permalink(); // Get the current page's URL

if (is_user_logged_in()) :
?>
    <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 certain roles. <a href="<?php echo wp_login_url($redirect_url); ?>">Log in</a> to access it.</p>
<?php endif; ?>

Here’s an explanation of the code in bullet points:

This code effectively checks if a user is logged in and, if not, encourages them to log in to access the restricted content, with a link that directs them back to the page they were trying to view.

View By Specific User Role

You can also limit the content to specific user roles if you’d like:

<?php
$allowed_roles = array('subscriber', 'editor', 'author'); // Add the roles you want to allow

$user = wp_get_current_user();
$redirect_url = get_permalink();

if (array_intersect($allowed_roles, $user->roles)) :
?>
    <h2><?php the_title(); ?></h2>
    <?php the_content(); ?>
<?php else : ?>
    <h2>Restricted Access</h2>
    <p>We're sorry, the content you are trying to reach is restricted to certain roles. 
    <a href="<?php echo wp_login_url($redirect_url); ?>">Log in</a> to access it.</p>
<?php endif; ?>

Here’s an explanation of the code in bullet points:

This code effectively restricts access to specific roles, and if a user doesn’t have one of the allowed roles, it prompts them to log in with a link that will redirect them back to the current page after logging in.

Select Your Template

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). This will restrict the page to logged-in readers or your defined role(s).

Exit mobile version