How To Force Users To Login Before Viewing Your WordPress

Do you wanna restrict your WordPress website just to some clients or registered users? You can easily force users to login before viewing your WordPress.

We can use auth_redirect() function to checks if user is logged in, if not it redirects them to login page. Upon logging in, they will be sent redirected to the page where they originally landed.

To restrict access to the your WordPress, drop the following into your current theme’s functions.php file:

function v_getUrl() {
  $url  = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http';
  $url .= '://' . $_SERVER['SERVER_NAME'];
  $url .= in_array( $_SERVER['SERVER_PORT'], array('80', '443') ) ? '' : ':' . $_SERVER['SERVER_PORT'];
  $url .= $_SERVER['REQUEST_URI'];
  return $url;
function v_forcelogin() {
  if( !is_user_logged_in() ) {
    $url = v_getUrl();
    $whitelist = apply_filters('v_forcelogin_whitelist', array());
    $redirect_url = apply_filters('v_forcelogin_redirect', $url);
    if( preg_replace('/\?.*/', '', $url) != preg_replace('/\?.*/', '', wp_login_url()) && !in_array($url, $whitelist) ) {
      wp_safe_redirect( wp_login_url( $redirect_url ), 302 ); exit();
add_action('init', 'v_forcelogin');

That’s it! This will keep unwanted audience away. This snippet comes straight from the Force Login plugin, and if you like this plugin/snippet then please consider donating some money to the author of the plugin. :)

9 thoughts on “How To Force Users To Login Before Viewing Your WordPress”

  1. Hey, I just added this code. Works really nice, BUT when you click “Lost your password?” on wp-login.php, you can’t get there now unfortunately. Any idea how to solve this?

  2. This works good for internal pages/posts, but not for the home page. How can this same functionally apply to the home page (is_home or is_front_page)?

Leave a Comment