Snippets / PHP
Hide the Entire Site Behind a Login Wall
function redirect_non_logged_in_users() {
if (!is_user_logged_in() && !is_page('login-registration')) {
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$encoded_url = urlencode($current_url);
error_log('Redirecting non-logged in user from: ' . $current_url); // Optional: for debugging
wp_safe_redirect('https://staging.voxel.guide/login-registration?redirect_to=' . $encoded_url); //BE SURE TO CHANGE THIS URL
exit;
}
}
add_action('template_redirect', 'redirect_non_logged_in_users');
function custom_login_redirect($redirect_to, $request, $user) {
if (isset($user->roles) && is_array($user->roles) && !empty($_REQUEST['redirect_to'])) {
return esc_url($_REQUEST['redirect_to']);
} else {
return admin_url();
}
}
add_filter('login_redirect', 'custom_login_redirect', 10, 3);
Discussion 3
Ask a question or share how you used this.
Doesn not work for me either. Your PHP code changes were not applied due to an error on line 133 of file wp-content/themes/voxel-child/functions.php. Please fix and try saving again. syntax error, unexpected token "function"
It's not working for me also. *Your PHP code changes were not applied due to an error on line 62 of file wp-content/themes/voxel-child/functions.php. Please fix and try saving again. syntax error, unexpected token "function"*
I'm getting error when saving the file.
What error? Where are you putting this code? It should be going in your child theme functions.php file and be sure to change the URL marked AND if your Login URL is different than line 2.