There are times that you would want a page only to be accessible for users which have logged into your the Wordpress user manager. Such as if you have a members only area of your website which is only for logged in users, you need to make sure that the page can not be seen by any users who haven't logged in yet. Wordpress has an inbuilt feature that allows you to easily manage users and roles for these users. Using the Wordpress user manager you can define different roles to your users but they will all be able to log into Wordpress and it doesn't matter which role they are assigned to. As you are using the built in Wordpress user manager then you can use a Wordpress functions to check if a user is logged in or not. This Wordpress function is called is_user_logged_in(). This function will return a true or false on if the user is currently logged in and works just like the code below.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?>
If the user is logged in then the message Welcome, register user! if the user is not logged in then you will get the message Welcome, visitor. Now we can use this function to create page templates that will make sure the page can only be seen from users who are logged in. First we need to create a new page template, which is done easily by creating a new PHP file in your theme folder and add the following comments to the top of the file.
<?php
/* Template Name: Admin Area for logged in users */
?>
When this file is saved you will see a new page template on the page template dropdown, now you can create new pages and assign them to use this page template.
We can now add the code to make sure that only logged in users are able to see this page. On your page template add the following code.
if ( !is_user_logged_in()) {
get_template_part('login');
exit;
}
get_header();
This code will make sure that the user is logged in, if the user is not logged in and tries to access this page then it will display the login theme template part. We then exit the code so then Wordpress doesn't run the rest of the code on this template page. You can also use another technique and instead of displaying the login template you redirect the user to the login page to your members only area.
if ( !is_user_logged_in()) {
wp_redirect( get_page_link(10) );
exit;
}
get_header();
This code does the same thing to check if the user is logged in but it will not display the login template page, instead we redirect to a page by using the get_page_link() function and pass in the page id of the members login page. This function returns the link to the page which we then use as the parameter for the Wordpress function wp_redirect(). That's all we need to do to redirect non-logged in users back to a login page for your sites members only area.