Create a new page template
The first step in requiring users to log in to view a page is to create a new page template by making a copy of your existing page.php template. I named mine “page_loggedin.php”.
Once you’ve done that you need to add a name to the template so that WordPress can recognize it as a new page template. Open the new file and add the following to the top (the template name can be anything you want. This is what you’ll select within the WordPress admin when creating your new page) :
<?php /* Template Name: Logged-In Users Page */ ?>;
Next you’ll need to add code to check if the user is logged in and, if not, to display an appropriate message to the user. So add this code just beneath the template name code we added in step 2:
<?php if(is_user_logged_in()):?>
Now go to the very bottom of the file and add the following code. This will call the wp_die() function to halt WordPress execution and display a notice to the visitor that he/she needs to first log in to view this page.
<?php else: wp_die('Sorry, you must first <a href="/wp-login.php">log in</a> to view this page. You can <a href="/wp-login.php?action=register">register free here</a>.'); endif; ?>
Save that new page template and upload it to your server.
That’s all the code we have to write. Next, create your new page and under “Page template,” select the new page template we just created.
Save your new page and that’s it. That page will now appear in any pages lists just like any other page on your site, but when a user who is not logged in clicks through, he/she will receive a notice similar to this:
Example of the message you get when trying to view a protected page