in Technology

Require login to view a WordPress site

On a WordPress site I have setup, I needed the ability to require user authentication before allowing anyone to view the website. To do this, just add the following snippet to the theme files:

global $user_ID;
if ($user_ID == '')
        header('Location: wp-login.php');

Now you will be greeted with the WordPress login page when entering the site without being authenticated! Note that if you want to be completely sure that no one can retrieve any information without authenticating, you need to either modify the WordPress core files, or use some other type of authentication outside of the WordPress code, such as a basic auth in the webserver.

Edit: I created a WordPress plugin which does this in a much better way – WP Require Auth plugin.