Select Page

Several years ago, I was tasked with creating a private WordPress website for internal use by a company. There were various plugins that worked in combination to basically achieve what I needed, but I chose to code a simple solution, so I would be able to easily change or add to the functionality in the future. I didn’t like the idea of having to hack up one or more plugins to get the exact functionality that I desired.

For this tutorial, I am going to use the Divi theme. Any theme can be used, but the steps below will vary depending on the theme you choose.

1. Create A Login Page

Create a new page using Divi’s “Blank Page” template. The only thing we require on this page is the Login module, although you may an unauthorized warning, etc. For this example, I am giving the login page a url of /login.

2. Obtain Your Login Page’s ID number

The simplest way to get your login page id number is to edit the page, and look up to your browsers address bar. You will see a variable in the address bar similar to “/post.php?post=101&action=edit”. In this example, 101 is your page id.

3. Create and Switch To A Child Theme

You must create a Divi child theme and switch to it as your active theme.

4. Insert the following code at the end of your child theme’s function.php file

function redirect_to_login() {
if(!is_user_logged_in() && !is_page(101)) { // check if visitor is logged in and not on login page
wp_redirect(‘/login’); // redirect user to login page
}
}

add_action( ‘wp_head’, ‘redirect_to_login’);

5. Test It Out

Logout or open a different browser and attempt to access the website. If you have successfully followed the instructions, you will be redirected to the login page you created.

**Don’t Need A Fancy Login Screen?

Skip to Step 3 and substitute the following code in Step 4 to redirect to the default WordPress login page:

function redirect_to_login() {
if(!is_user_logged_in()) { // check if visitor is logged in
wp_redirect(‘/wp-login.php’); // redirect user to default login page
}
}

add_action( ‘wp_head’, ‘redirect_to_login’);

Troubleshooting

Redirect Loop – If it appears that the website keeps redirecting over and over or your browser notifies you that you have an endless loop, you most likely used the wrong page id in the redirect_to_login function.