WordPress – Only logged in users can view your website

March 18, 2016 by Pat - Comments - 1 min read

WordPress

I had a WordPress site requirement where only logged in users could see the site and it’s contents. I came across this bit of code a few years ago and found it to be helpful. Place it into your functions.php and when a visitor comes along who is not logged in, it’ll redirect them to the wp-login.php page to login. Once logged in, then they can view the site without being blocked.

This is an example where it can help keep unwanted visitors away from the content of your site.

It’s been working great and I wanted to share it.

<?php

// Redirect users who arent logged in...
function members_only() {
    global $pagenow;
    // Check to see if user in not logged in and not on the login page
    if( !is_user_logged_in() && $pagenow != 'wp-login.php' )
          auth_redirect();
}
add_action( 'wp', 'members_only' ); 

?>
Share this post:

About Pat

I'm an I.T. systems engineer by day and in my spare time I code. I've made WordPress websites and plugins, weewx extensions and static html sites using Jekyll. I'm a technologist at heart and I enjoy tinkering on many different technology projects. Here on my site you will find some of the projects I've worked on, and other random bits of knowledge that I hope help someone along the way.

mentions