Redirect WordPress user if not logged in

Quite often I have requirements to redirect users if they are not currently logged in to a site. This could be for numerous reasons, but a popular one would be to redirect all visitors to a coming soon page while allowing admins to login in and view the site.

This is accomplished by adding the following snippet to the very first part of your template. This could be your header.php or if your page templates have the in them, you will need to add this into each. This snippet basically has to go at the very top of your pages – whether that be the head.php, header.php or a page template.

if(!is_user_logged_in() ) {
    wp_redirect( '/your-url', 302 );
    exit;
}

So, let’s say you had a comingsoon HTML page on the server, say in the root directory. You could check the user is logged in and if not redirect them to that page…:

if(!is_user_logged_in() ) {
    wp_redirect( './comingsoon.html', 302 );
    exit;
}

These snippets assume you are logging into your site via the admin area (wp-login.php or /wp-admin). However, if your site has a front-end login only via a plugin like Paid Memberships Pro or Theme My Login or such, then your login must be done in the front-end only and you will still need to access this page. We will then have to wrap our redirect with another check that states to run it only if we’re not on the login page.

In this instance you would need to allow this page to be viewed without having to be redirected (as we need to access the login page). So this would be done like so:

if(!is_page('Login') ) {
    if(!is_user_logged_in() ) {
        wp_redirect( './comingsoon.html', 302 );
        exit;
    }
}

Hope this helps!

Useful post? Share it

Leave a Reply

Your email address will not be published.