Do you want to restrict access on your WordPress website to registered users only? You can easily force users to login before viewing your WordPress website.
We can use the auth_redirect() function to check if a user is logged in. If it’s not, it redirects them to the login page. Upon logging in, they will be redirected back to the page where they originally landed.
To restrict access to your WordPress website, add the following code snippet to your WordPress website:
function v_getUrl() {
$url = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http';
$url .= '://' . $_SERVER['SERVER_NAME'];
$url .= in_array( $_SERVER['SERVER_PORT'], array('80', '443') ) ? '' : ':' . $_SERVER['SERVER_PORT'];
$url .= $_SERVER['REQUEST_URI'];
return $url;
}
function v_forcelogin() {
if( !is_user_logged_in() ) {
$url = v_getUrl();
$whitelist = apply_filters('v_forcelogin_whitelist', array());
$redirect_url = apply_filters('v_forcelogin_redirect', $url);
if( preg_replace('/\?.*/', '', $url) != preg_replace('/\?.*/', '', wp_login_url()) && !in_array($url, $whitelist) ) {
wp_safe_redirect( wp_login_url( $redirect_url ), 302 ); exit();
}
}
}
add_action('init', 'v_forcelogin');
Code language: PHP (php)
Alternatively, if you are not comfortable adding code snippets to your website, I recommend installing this plugin instead.
How do i retrict login to all pages except the home?
This function doesn’t seems to work anymore. I’ll do some research later on to find out why it’s not working. Is it working on your site?
Any update on this ? Thx!
Never got time to do some research on this issue. Is it working for you?
I have not tried yet. I think i will now rather install the plugin http://wordpress.org/plugins/wp-force-login/
Thanks for sharing that plugin. I just looked into that plugin and updated the article with a code which works :)
Thank you!
Hey, I just added this code. Works really nice, BUT when you click “Lost your password?” on wp-login.php, you can’t get there now unfortunately. Any idea how to solve this?
This works good for internal pages/posts, but not for the home page. How can this same functionally apply to the home page (is_home or is_front_page)?
I think you must place code to template_redirect hook rather than init. because if you placed on init action, there will block WP Rest API also.