Estimated Reading Time: 2 min
To redirect users who are not logged in to a specific page in WordPress, you can add the following code to your theme’s functions.php
file:
Redirect Non-Logged-In Users
function redirect_non_logged_in_users() {
// Check if the user is not logged in and not on the login or registration page
if (!is_user_logged_in() && !is_page(array('login', 'register'))) {
// Redirect to the login page or another specified page
wp_redirect(home_url('/wp-login.php')); // Change '/wp-login.php' to your desired URL
exit; // Terminate further execution
}
}
add_action('template_redirect', 'redirect_non_logged_in_users');
How It Works
is_user_logged_in()
: Checks if the user is logged in.is_page()
: Excludes specific pages from the redirection (like the login or registration page).wp_redirect()
: Redirects users to the specified page (e.g.,/wp-login.php
).exit
: Stops further processing after the redirection.
Customization
Change Redirect URL: Modify the URL in the home_url('/wp-login.php')
to point to your login or any other page.
Exclude Additional Pages: Add more page slugs to the is_page()
array:
if (!is_user_logged_in() && !is_page(array('login', 'register', 'about', 'contact'))) {
wp_redirect(home_url('/wp-login.php'));
exit;
}
Exclude Admin Area: To ensure non-logged-in users are redirected only for frontend pages, check:
if (!is_user_logged_in() && !is_admin() && !is_page(array('login', 'register'))) {
wp_redirect(home_url('/wp-login.php'));
exit;
}
Notes
- Ensure the redirect URL (
/wp-login.php
) is publicly accessible to non-logged-in users. This could be the WordPress default login page or a custom page. - If you’re using a custom login plugin or membership system, make sure to align the URL and conditions accordingly.
Let me know if you need help adapting this further!
Discover more from Be-smart
Subscribe to get the latest posts sent to your email.