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' ); 

?>
Disclosure: Some of the links on this website are affiliate links. This means that, at zero cost to you, I will earn an affiliate commission if you click through the link and finalize a purchase.
Share this post: