WordPress中如何将所有未登录访客重定向至指定页面?
Redirect Unlogged WordPress Visitors to Your Custom Login Page
Hey there! Let's get this sorted for you—redirecting unlogged visitors to your custom login page is totally doable with a couple of solid methods. Here are the most reliable ways to pull it off:
Method 1: Add Custom Code to Your Theme (Flexible & Free)
This is my go-to method because it gives you full control without relying on plugins. Just follow these steps:
- Open your WordPress dashboard, head to Appearance > Theme File Editor.
- On the right sidebar, find and click
functions.php(pro tip: use a child theme'sfunctions.phpinstead of your main theme's—this way, your changes won't get wiped when the theme updates). - Paste this code at the bottom of the file:
function redirect_unlogged_users() { // List pages visitors can access without logging in $allowed_pages = array( '/my-custom-login/', // Replace with your custom login page's slug/URL '/lost-password/', // Password reset page (adjust if needed) // Add other allowed pages here, e.g., '/public-about-page/' ); // Check if user isn't logged in and current page isn't allowed if (!is_user_logged_in() && !in_array($_SERVER['REQUEST_URI'], $allowed_pages)) { // Redirect to login page, and send users back to their original destination after login wp_redirect(home_url('/my-custom-login/') . '?redirect_to=' . urlencode($_SERVER['REQUEST_URI'])); exit; } } add_action('template_redirect', 'redirect_unlogged_users');
- Don't forget to replace
/my-custom-login/with your actual login page's URL slug. - Always back up your
functions.phpbefore editing—one tiny typo can take your site down temporarily!
Method 2: Use a Plugin (No-Code Option)
If you'd rather avoid messing with code, a lightweight plugin will handle this in minutes:
- Install and activate the WP Force Login plugin (it's free and well-maintained).
- After activation, go to Settings > Reading and scroll to the bottom of the page.
- In the "Redirect URL" field, paste your custom login page's full URL.
- Save changes—and that's it! The plugin will automatically redirect all unlogged visitors to your login page, and it handles the return URL so users land back where they wanted to go after logging in.
Critical Things to Remember
- Test in Incognito Mode: Always test this in a private/incognito window to avoid being logged in as an admin and missing issues.
- Avoid Infinite Loops: Make sure your custom login page is included in the allowed pages (either via the code's
$allowed_pagesarray or the plugin's settings)—otherwise, visitors will get stuck in a never-ending redirect loop. - Clear Cache: If you use a caching plugin (like WP Rocket or W3 Total Cache), clear your site's cache after setting this up to ensure the redirect works right away.
内容的提问来源于stack exchange,提问作者Gaurav Tikhile
相关产品推荐
相关产品推荐

