如何编写WordPress PHP函数,仅允许未登录用户访问3个指定页面?
Got it, let's fix this. The Restricted Site Access plugin is solid but doesn't cover the lost password page out of the box, so a custom PHP snippet will give you full control. Here's how to approach it:
Core Approach
We'll hook into WordPress's template_redirect action (fires right before the page template loads) to check two things:
- Is the user not logged in?
- Is the current page not one of your allowed pages?
If both are true, we'll redirect them to the login page (or show a 403 if you prefer—adjust as needed).
Full Code Snippet
Add this to your theme's functions.php file, or a custom plugin (recommended to avoid losing changes during theme updates):
function restrict_non_logged_in_access() { // Skip checks if user is already logged in if (is_user_logged_in()) { return; } // Define your allowed custom page slugs—match these to your site's actual pages $allowed_pages = array( 'login', // Custom login page slug 'register', // Custom registration page slug 'lostpassword' // Custom lost password page slug ); // Check if current page is one of the allowed custom pages $current_page_slug = get_query_var('pagename'); if (in_array($current_page_slug, $allowed_pages)) { return; } // Also allow default WordPress auth endpoints (wp-login.php with specific actions) $current_url = $_SERVER['REQUEST_URI']; if (strpos($current_url, 'wp-login.php') !== false) { $allowed_actions = array('register', 'lostpassword', 'resetpass'); $action = isset($_GET['action']) ? $_GET['action'] : ''; // Allow wp-login.php itself (default login) and the specified actions if (empty($action) || in_array($action, $allowed_actions)) { return; } } // Allow AJAX requests to prevent breaking frontend dynamic features if (defined('DOING_AJAX') && DOING_AJAX) { return; } // Redirect to login page, with a redirect back to the original page after login wp_redirect(wp_login_url(get_permalink())); exit; } add_action('template_redirect', 'restrict_non_logged_in_access');
Key Adjustments for Your Site
- Custom Page Slugs: If your login/register/lost password pages use different slugs (e.g.,
sign-ininstead oflogin), update the$allowed_pagesarray to match. - Redirect Target: The
wp_login_url(get_permalink())sends users back to the page they tried to access after logging in. To redirect to a fixed page instead, replaceget_permalink()with a URL likehome_url('/login/'). - Default Auth Pages: The code handles the default WordPress login/register/lost password endpoints (like
wp-login.php?action=lostpassword) so you don't lose access if you're using the default system alongside custom pages.
Why This Beats the Plugin
This snippet gives you granular control over exactly which pages are allowed—no plugin limitations. It also covers both custom pages and the default WordPress authentication flow, so you don't have to choose between the two.
内容的提问来源于stack exchange,提问作者Iulian Sandu

