Recently I was working on a project that I needed to create a members section and keep all content applicable to members locked out from everyone else. I wanted to make this process as basic as possible so that any intermediate WordPress developer could understand it and make their own “members only section”.
The concept is rather basic, you will create pages or posts (really it can be just about any type of content) and check to see if the user is logged in or not. If the user is logged in display X, and if they are not logged in display X. For this example, we are going to create an account center that only people logged in can view. Here we go:
Step 1: Setup a custom page template
Create a custom page template. (If you are unsure how to do this you can read my previous post on how to create custom page templates) Name your custom page template “Account Center” like below and add the basic functions to call your header and footer as any page template would have.
<?php /* Template Name: Account Center */ ?> <?php get_header(); ?> <?php get_footer('account'); ?>
Step 2: Check if user is logged in
We are now going to check if a user is logged in, and if they are we will display the account page to them. Here is the code added to our page template we have already setup:
<?php /* Template Name: Account Center */ ?> <?php if(is_user_logged_in()) : // checks if user is logged in. ?> <?php get_header(); // if the user is logged in, get header. ?> ... // Your HTML for your page template here. <?php get_footer('account'); // if the user is logged in, get account center footer ?> <?php else : // if the user is not logged in. $url = '/wp-login.php'; // sets $url variable to redirect to login form. You can set this to any URL you want. header("Location:$url"); // takes user to $url when header is called. endif; // end if statement. ?>
Now go into the backend of WordPress and create a page called Account and select the page template “Account Center”. You should now only view that URL if you are logged in. I will expand on this post next time and show you how to create a custom login page, how to display specific user information within the account center, etc so stay tuned!
If you have any other secrets or insight that you have used we would love to hear them.