Only logged in users can view your website

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

?>
https://obrienlabs.net/wordpress-logged-users-can-view-website/
  • Categories