3

I am developing a theme. I need to have a user login system, that allows users to see all contents of the application and interact with it only after they login (not admin panel login).

I need to redirect all traffic at start to a login.php page instead of wordpress "home" (page.php), if users are not logged in. Otherwise land in "home".

What is the right way to do that in wordpress without using plugins?

6
+50

You can use the wp_loaded hook to push all non-logged-in traffic to the login screen. Note how I've passed $_SERVER['REQUEST_URI'] to wp_login_url() - this is passed as a URL parameter to the login page, and once a user successfully signs in, they'll be redirected back to the URL they were originally trying to visit.

function wpse_178177_redirect_to_login_if_guest() {
    if ( ! is_admin() && ! is_user_logged_in() && $GLOBALS['pagenow'] !== 'wp-login.php' ) {
        wp_redirect( wp_login_url( $_SERVER['REQUEST_URI'] ) );
        exit;
    }
}

add_action( 'wp_loaded', 'wpse_178177_redirect_to_login_if_guest' );
  • 2
    Why don't use 'wp_loaded' hook? It's late enough to being able to recognize user and, on the countrary of 'template_redirect', is early enough to avoid a not needed db query. – gmazzap Feb 18 '15 at 15:05
  • 1
    You could, of course. But template_redirect offers the simplicity of not having to check ! ( is_admin() || defined( 'DOING_AJAX' ) && DOING_AJAX || $GLOBALS['pagenow'] === 'wp-login.php' ), which IMO looks a little messy. Not to mention you're now hijacking WordPress fairly early on, and possibly breaking other plugins/themes. That's exactly why the template_redirect action exists. – TheDeadMedic Feb 18 '15 at 15:11
  • 2
    'template_redirect' is there to make redirects that need to access query data. Moreover, actually you don't need to check for ajax because is_admin() is always true on ajax requests. So the additional effort it's just a quite simple if, but the performance improve. Also, preventing plugins to do things they do not have to do (because user is not allowed) is just an additional reason to act first. – gmazzap Feb 18 '15 at 15:43
  • 1
    Sure thing, updated. But make sure nothing is manually loading wp-load.php (like some plugins & 3rd party's), otherwise they'll be affected too. – TheDeadMedic Feb 18 '15 at 15:57
  • 3
    I +1ed, but.. the check for $GLOBALS['pagenow'] === 'wp-login.php' should be there. :) – gmazzap Feb 18 '15 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.