How it works...

In order to protect the entire site with a single password, we have to check the password on each request to the frontend or backend. So, we choose WordPress's init action for the implementation as it's executed on all requests to the site. 

In step 2, we used a callback function called wpcpp_ch12_global_password_protection on the init action. Inside the function, we added a simple HTML form containing a label, a password field, and a submit button. Also, we used an additional <DIV> element to show the error messages to the user.

In step 3, we added the code to capture and verify the password. The process of requesting the password on each screen is not a user-friendly solution. Therefore, once the user provides the correct password we have to let the user access the site for a considerable time period without requesting the password again. So, we have to use the browser cookies to store the verification status and let the user access the site until the cookie expires. So, we used the following lines of code to check if the cookie for the password is set:

 if(isset($_COOKIE['wpcpp_ch12_password_verified'])) {
return;
}

Once the cookie is set, we return the request and let the user access the site. Then, we defined a variable for the error message. Next, we added the global password of the site using $global_password and captured the user-submitted password value to the $user_global_password variable. Then, we verified the submitted password against the password defined in the $global_password variable. Once the passwords match, we set the cookie with the name to wpcpp_ch12_password_verified and the value as verified for 5 minutes (300 seconds). Then, we return from the function allowing WordPress to load the requested URL.

Now, the user will be able to access the site for five minutes without providing the password. Once the cookie expires, the user will again see the form to submit their password and get access.

Before moving on to the next recipe, remove the code for this recipe inside the WPCookbook Chapter 12 plugin.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset