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. 🙂