Many websites make money by having membership content areas. There maybe special articles, podcasts or many other things that people only get access to if they have paid to become a member or just signed up to receive newsletters or other promotions. While there are many plugins that do this, learn how to create a member section in WordPress without a plugin.
First, go to your Theme Editor by going to Appearance -> Editor. You will either need to create a new page template or use one that is already created.
If you want to create one, find an existing template in your theme that you want to use and copy it. Then either through FTP or in your host’s file manager, create a file in your wp-content/themes/yourTheme directory called member.php.
Then in your Theme Editor, copy all of the code from the existing page template into member.php.
At the top of the page, just under <?php
paste in:
/*
Template Name: Member Page
*/
This will give your template a name and allow you to select it on each individual page you create.
Next before any other code, paste in:
if ( is_user_logged_in() ) {
This will check to see the user is logged in or not to WordPress. I suggest allowing people to register as subscribers only. If they are logged in, the next bit of code will execute, which is your page template.
Then at the very end, probably after <?php get_footer(); ?>
, paste this in:
}
else {
// get the current page id
$current_page_id = $wp_query->get_queried_object_id();
// redirect to the login screen with a redirect back
header( 'Location: /wp-login.php?redirect_to=%2F?p=' .$current_page_id);
}
?>
This code will execute only if the user isn’t logged in. First it will grab the current page the user tried to view. Then it will redirect them back to the login screen with another redirect as a $_GET parameter, which will redirect them back to the page they came from if the login is successful.
There you go, a simple membership area using WordPress users. This can also be used for custom admin areas or many other uses.
Photo by Andrew Neel on Unsplash
Bjorn says
How safe is this? Is there any way a hacker can get past the redirect and view the page?
Eric Debelak says
Hi Bjorn, good question. The
is_user_logged_in()
function is a built in WordPress function tested in millions of websites for many years. Is it secure enough for a banking application? Probably not. But is it secure enough for a membership site? Definitely. So that function will assure that the user is logged in. For the content, PHP renders the HTML page that is sent to the browser on the server, so if the user isn’t logged in, the server simply won’t render it and the user can’t see it. I hope that answers your question!