Monday, October 21, 2013

Force Login to View WordPress Blog Pages

I was recently working on a private / "closed" website that featured WordPress.  User management is a must and content can only be seen if the user is logged in.  I was shocked to find that WordPress didn't provide an option to accomplish this task.  Luckily a quick snippet in the header of my template allowed me to force login to view content:
// Require login for site
get_currentuserinfo();
global $user_ID;
if ($user_ID == '') { 
 header('Location: /wp-login.php'); exit(); 
}
The get_currentuserinfo() function provides a huge object with information about the user.  We then look at the user_ID variable to see if the user's ID is defined -- if not, they aren't logged in and we should send them to the login page!
Do remember that your header() calls must take place before any content is pushed to the page, so I recommend adding this content at the very top of your header.php file. There's also a WordPress plugin to accomplish this task.