Forcing Users to Login to a WordPress Site

WordPress is an increasingly more popular blog platform. Because it is so customizable and so robust, some want to sue it for an intranet or a more private workspace. I have one such site and I was looking for a way to force people to login before viewing the site. I had a hard time finding out how to make it work, so I have posted the answer here.

Previously, I was using WordPress 2.3 and found a post in an obscure place that had PHP code looking for cookies to determine whether a visitor was logged in. If they were not, then there was a redirect to the login page. All this code was added in the top of the file header.php so that it would execute first and redirect if needed.

After upgrading to WordPress 2.5, the code I was using to force a login to the site was no longer working. It gave an infinite loop in the redirection to the base page and I received an error instead of a web page. It appears to be from the code used to determine if a cookie was present on the system. When I removed the code, all worked normally.

The code below is adjusted to work with version 2.5 and will send all users without valid cookies to the login page. Note that I used the included function, is_user_logged_in().

if (!is_user_logged_in()) {
wp_redirect(get_option('siteurl') . '/wp-login.php?redirect_to=' . urlencode($_SERVER['REQUEST_URI']));
? >

NOTE: Do not put spaces inbetween the characters. I included spaces here to properly show the code.

Let me know if you have other ideas.


  1. Great job on this. I am installing it now. Did you mention anywhere what file this snippit should be placed?

  2. Yes, see in the second paragraph I indicate that this code is in the top of the header.php file. Each WordPress theme should have this file.

Leave a Comment