Force Login to View WordPress Blog Pages

By  on  

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.

Recent Features

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    Welcome to My New Office

    My first professional web development was at a small print shop where I sat in a windowless cubical all day. I suffered that boxed in environment for almost five years before I was able to find a remote job where I worked from home. The first...

Incredible Demos

Discussion

  1. Ahmed Samir

    I like the handy solution. However, there’s a number of plugins for this that allows more customization like a custom page/text and redirection etc….

  2. Pretty nifty snippet, thanks.

  3. There is a pretty useful function for that, called is_user_logged_in(), which does exactly what you might think it might do.

    I am not sure if the location you specified in the header might give problems if blog uses the so-called SEO-friendly URLs like “blog.com/foo/bar/” for posts and/or pages. So in order to prevent bad redirections, there is also a WordPress function called wp_login_url(), which brings us to this untested snippet:

    if (!is_user_logged_in()) {
        header('Location: '.wp_login_url(get_permalink()));
        exit;
    }
    
    • That seems much more flexible, awesome!

    • Marcaum54

      Ty man, just what i needed ;)

  4. You could also place this in your functions.php file:

    function walled_garden()
    {
    	if( ! is_user_logged_in() )
    		wp_redirect( '/wp-login.php' );
    }
    add_action( 'get_header', 'walled_garden' );
    
  5. I think we also need to check for is_admin().
    I am not sure is_user_logged_in() will return true in case of admin logged in. What you think?

    • Because the admin is an user, it will return true, if he/she is logged in. I checked the function for it to be true. As a matter of fact is_user_logged_in() does almost the same as David suggested above. It gets the user-details and checks if the ID equals 0.

  6. @KMB: thx KMB for explaining…

  7. S Hamzah

    Hello. Thanks for this.

    It works fine for me, until I try to recover my password. It seems like the password lost and found link is considered as other url, so it still redirected to login page. Is it just me or do we need to add some more snippets?

  8. Tim

    I get this error when I use the code above.

    Warning: Cannot modify header information – headers already sent by (output started at /home/content/92/7103392/html/wordpress/wp-content/themes/twentyten/venue_event_add.php:6) in /home/content/92/7103392/html/wordpress/wp-content/themes/twentyten/venue_event_add.php on line 23

    Any suggestions?

  9. Tim

    Resolved warning by adding this line below to the functions.php located in what theme you are using.

    ob_start();

  10. Hi David. Great post and it answers part of my question.

    Furthermore, can the loop be customised to only show posts that are of a specific type? I am wondering if I can use WordPress as a way to communicate with clients based on their login and only show posts that are targeted at their company/login. Like a bug tracker of sorts.

    Thanks
    Steven

  11. The plugin you linked to hasn’t been updated in a few years so your tip I hope will be helpful for our college’s website over the holidays while we move to WordPress.

  12. So, when I used the plugin suggested in a WPMU, all the pages were put behind the login wall… this code worked like a charm because I only wanted to cut access to a single sub blog … so put it in that sub blog theme … :) thanks !

  13. Nick

    Where would you recommend putting this code so that it runs ALWAYS? I get the 404 error if I try and access a page that doesn’t exist. I would rather redirect to login and only show 404 if the user is logged in. Of course I want this for all errors, so I don’t want to just add it to the 404 page too. Any suggestions on a more global place to put it other than the template header?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!