0

Here is my code for restrict my wordpress site:

function restrict_access_if_logged_out(){
  if (!is_user_logged_in() && !is_home()){
    $redirect = home_url() . '/wp-login.php?redirect_to=' . esc_url($_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]));
    wp_redirect( $redirect );
    exit;
  }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

Now I want to add one exception for example for URL: example.com/home-page.

2
  • Do you have a static front page set. As your code stands, in plain english it says, if the user is not logged in and if he is not on the homepage, redirect the user. What exactly do you need Commented Sep 5, 2014 at 9:46
  • Sorry, I did not explain well :( I answer the question if anyone cares.
    – Neil
    Commented Sep 5, 2014 at 14:55

2 Answers 2

4

I wanted to restrict my website except a specific page. This is my solution:

function restrict_access_if_logged_out(){
  global $wp;
  if (!is_user_logged_in() && !is_home() && ($wp->query_vars['pagename'] != 'name-of-page') ){
    $redirect = home_url() . '/wp-login.php?redirect_to=' . esc_url($_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]));
    wp_redirect( $redirect );
    exit;
  }
}

Only I added this: && ($wp->query_vars['pagename'] != 'name-of-page') in IF clause and a global variable $wp for exclude a specific page. This method avoid redirect when the pages is 'name-of-page'.

My inspiration here.

And thanks @PieterGoosen for your solution in your post. :)

2
  • Hope that you understand me :)
    – Neil
    Commented Sep 5, 2014 at 15:06
  • Thanks for posting your solution, and +1 for the credits Commented Sep 5, 2014 at 15:13
0
function restrict_access_if_logged_out(){
  if (!is_user_logged_in() || !is_home()){
    $redirect = home_url() . '/wp-login.php?redirect_to=' . esc_url($_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]));
    wp_redirect( $redirect );
    exit;
  }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

Rather than && use || with your conditional tag.

4
  • It doesn't work :( I don't know why
    – Neil
    Commented Sep 5, 2014 at 9:23
  • I don't think the problem is with AND or OR operators here. See my post here about this operators :-) Commented Sep 5, 2014 at 9:52
  • I had precisely found the solution to the problem but in a different way. Thanks anyway. If you want to answer the question, I will accept. Or I answer with my solution.
    – Neil
    Commented Sep 5, 2014 at 13:06
  • post it if you like Commented Sep 5, 2014 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.