How to password protect your entire WordPress site

How to password protect your entire WordPress site

There are more ways to protect your entire WordPress site, but if you want to make the site accessible only to registered users then you should apply the WordPress login form to any page before it gets loaded.

While there are plugins to do this, password protecting the entire site is done easily by coding inside the used template.

To start, locate and edit the header.php file inside the template. The idea is that if the the visitor is not logged in, replace the default html with the login form.

Open the header.php file and add to the very beginning the following code that checks if the current user has an user id:

 <?php $current_user = wp_get_current_user();
if ($current_user->ID == '') {
exit();
} ?>

If you open the site and you are not logged in it should show an empty page as the execution exits. Let’s insert the usual HTML tags on any page, some titles and some styling:

 <?php $current_user = wp_get_current_user();
if ($current_user->ID == '') {

print '
<html>
<head>
<title>My site</title>
<style>
body {text-align:center;font-family:sans-serif;font-size:16px;color:#333;padding-top:25px;}
h2 {font-size:18px;font-weight:normal;margin:15px 0;}
</style>
</head>
<body>
<h1>My site title</h1>
<div id="login">;
</div>
</body>
</html>';

exit();
} ?>

Let’s add the login form. For this we are going to use the wp_login_form functionality inside the div with the id=”login”. First we should break the print string in 2 parts, then add the wp_login_form:

<div id="login">';

wp_login_form('label_username=Username&label_password=Password&label_remember=Remember me on this device');

print '</div>

This is how it should look at this point, and it’s working too!
The only thing that is missing right now is error messages. Let’s add some. First let’s check if there is any error and if there is, we should check if it’s an username error or a password error. Let’s add the following code just below the wp_login_form:


if($loginError && $u->get_error_code() === 'invalid_username')
{
echo "The username is incorrect.";
}
if($loginError && $u->get_error_code() === 'incorrect_password')
{
echo "The password is incorrect.";
}