Sometimes, you would want to lock the site completely, and allow it only to registered users. Also, you may want to redirect the front-end login requests to a custom WP Page with a custom login form, other than going to the default /wp-login.php
page, like below:
That can be easily achieved by writing a simple function in your theme’s functions.php
file, that will hook on the template_redirect hook:
// restrict to logged in users only add_action( 'template_redirect', function() { // Front end only and prevent redirections on ajax functions if ( is_admin() || wp_doing_ajax() ) { return; } $page = '/login'; // Redirect all pages to the login page if user isn't logged in if ( ! is_user_logged_in() ) { if(! is_page('Login') && ! is_page('Privacy Notice') ) { wp_redirect( esc_url( $page ), 307 ); exit; } } } );
As you can see, a special check is performed on top, to see if the request is coming from the front-end or the admin back-end, as well as if it is a WordPress Ajax request.
From the above example, it is obvious that it is very easy to skip some pages, that you want to stay public, like the very Login page, Privacy Policy, or Terms & Conditions, etc.