You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress未登录用户跳转自定义登录页代码失效求助

Fixing Unlogged User Redirect in WordPress (When Your Functions.php Code Fails)

Hey there! Let's tackle this redirect issue for unlogged users in WordPress. I've helped tons of developers troubleshoot exactly this problem, so let's break down why your initial code might not have worked and get you a reliable solution.

Common Reasons Your Code Didn't Work

Before we jump into the fix, let's cover the most frequent culprits:

  • Wrong hook timing: If you used a hook that fires before WordPress has loaded the user state (like init with too high priority), the is_user_logged_in() check won't work correctly.
  • No excluded pages: If you didn't exclude your custom login page (or default auth pages), you'd create an infinite redirect loop—and WordPress usually blocks that silently.
  • Cache interference: Caching plugins (like WP Rocket, W3 Total Cache) often serve static versions of pages, skipping your PHP logic entirely.
  • Theme/plugin conflicts: Another plugin or your theme's code might be overriding your redirect function, or using the same hook with a higher priority.

The Correct Redirect Implementation

Here's a robust code snippet you can add to your theme's functions.php file (or a custom plugin, which is safer than modifying theme files directly). This fixes all the common issues:

function redirect_unlogged_users_to_custom_login() {
    // Define pages to EXCLUDE from redirect (prevent loops)
    $excluded_endpoints = array(
        'custom-login', // Replace with your custom login page's slug
        'wp-login.php',
        'wp-register.php',
        'lostpassword',
        'resetpass'
    );

    // Get current page's endpoint/slug
    $current_path = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

    // Only redirect if user is NOT logged in and not on an excluded page
    if ( !is_user_logged_in() && !in_array($current_path, $excluded_endpoints) ) {
        // Replace with your custom login page URL
        $login_url = home_url('/custom-login/');
        wp_redirect($login_url);
        exit; // Critical: Stops further execution to ensure redirect works
    }
}

// Use the template_redirect hook—fires right before templates load, perfect for redirects
add_action('template_redirect', 'redirect_unlogged_users_to_custom_login');

Key Notes on This Code:

  • template_redirect hook: This is the ideal hook for redirects because it fires after WordPress has loaded user data but before any page content is sent to the browser.
  • Excluded pages: We explicitly skip auth-related pages to avoid infinite loops. Make sure to replace 'custom-login' with your actual login page's slug (check the page editor in WordPress admin to find this).
  • exit statement: Always add this after wp_redirect()—without it, WordPress might continue executing code and the redirect could fail.

Troubleshooting If It Still Doesn't Work

If the code above doesn't do the trick, run through these checks:

  1. Disable caching: Temporarily turn off all caching plugins and clear your browser cache. Cached pages won't trigger your PHP code.
  2. Test for conflicts: Switch to a default WordPress theme (like Twenty Twenty-Four) and disable all plugins. If the redirect works, re-enable them one by one to find the conflicting one.
  3. Verify page slugs: Double-check that the slug you added to $excluded_endpoints matches your custom login page's actual slug. A typo here will break the exclusion.
  4. Check for PHP errors: Enable WordPress debug mode by adding these lines to your wp-config.php file:
    define('WP_DEBUG', true);
    define('WP_DEBUG_LOG', true);
    
    Then check the wp-content/debug.log file for any errors related to your function.
  5. Adjust hook priority: If another function is using the same hook, try changing the priority in add_action (the third parameter). For example:
    add_action('template_redirect', 'redirect_unlogged_users_to_custom_login', 1); // Lower number = runs earlier
    

内容的提问来源于stack exchange,提问作者Gianni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:17:54