Overview
This code snippet is designed to restrict access to a WordPress site to logged-in users only. It also disables search functionality for users who are not logged in. Non-logged-in users are automatically redirected to the login page.
What It Does
- Restricts Site Access: Non-logged-in users are redirected to the login page if they attempt to access any part of the site, except the login and registration pages.
- Disables Search for Non-Logged-In Users: The search functionality is disabled for non-logged-in users, redirecting them to the login page if they attempt to use it.
Code Explanation
Restricting Site Access
function wbcom_protect_site_for_members_only() {
// Check if the user is not logged in
if (!is_user_logged_in()) {
// Define pages that should be accessible without login
$accessible_pages = array(
'login',
'register',
'wp-login.php'
);
// Get the current page slug
$current_page_slug = basename($_SERVER['REQUEST_URI']);
// Check if the current page is not in the list of accessible pages
if (!in_array($current_page_slug, $accessible_pages)) {
// Redirect all non-logged-in users to the login page
wp_redirect(wp_login_url());
exit;
}
}
}
add_action('template_redirect', 'wbcom_protect_site_for_members_only');
This function checks if a user is logged in. If the user is not logged in, it redirects them to the login page, unless they are on the login or registration pages.
Disabling Search for Non-Logged-In Users
// Disable search functionality for non-logged-in users
function wbcom_disable_search_for_non_logged_in_users($query) {
if (!is_user_logged_in() && $query->is_search()) {
// Redirect to login page if a non-logged-in user tries to search
wp_redirect(wp_login_url());
exit;
}
}
add_action('pre_get_posts', 'wbcom_disable_search_for_non_logged_in_users');
This function checks if the current query is a search query and whether the user is logged in. If the user is not logged in and they attempt a search, they are redirected to the login page.
How to Implement
- Copy the code provided above.
- Open your WordPress theme’s
functions.phpfile. - Paste the code into the file.
- Save the file.
Once implemented, non-logged-in users will only have access to the login and registration pages, and they will not be able to use the search functionality.
Notes
- You can customize the
$accessible_pagesarray to add more pages that non-logged-in users should be able to access. - Ensure that your login and registration pages are properly set up to allow users to register or log in.
This code can be used to create a private, members-only website where all visitors must log in to access content, while also preventing non-members from using the search feature.
