Well I am newbie to WP and the question may sound duplicate but even after trying for few days I can not make this work.

I have integrated a custom login and registration form in my WP site which is different form usual WP login and register forms.

I need to perform the following actions

  1. Redirect user to login page if directly accessed any Page URL
  2. Redirect user to home page if directly accessed login/register URL.

For redirecting user to home page if tries to access login/register URL after being already logged in, I have used below code

function checkUser(){

$user = wp_get_current_user();
if ( empty( $user->ID ) )
        return false;

    return true;   

function __construct(){
    add_action('init', array($this, 'checkUser'));

Even if I use wp_redirect(site_url());exit;; that do not seem to work and it goes into infinite loop.


  • use is_user_logged_in()instead.
    – Sisir
    Commented Jan 20, 2015 at 5:13
  • The problem is that is_user_logged_in is a pluggable function, and is therefore loaded after this plugin logic is called. The solution is to make sure that you don't call this too early. This can be done by wrapping this logic in a function and calling it from 'init' Commented Jan 20, 2015 at 5:16
  • use template_redirect hook. Although it may not solve infinite redirect issue. Need to see more codes.
    – Sisir
    Commented Jan 20, 2015 at 5:21
  • @Sisir thanks for responding, but it still goes into infinite loop. Could you help with these ? Commented Jan 20, 2015 at 5:29
  • share more code.. where did you instantiate the class?
    – Sisir
    Commented Jan 20, 2015 at 5:35

1 Answer 1


Here is from my previous project. The function is hooked into the template_redirect action. Inside the function there are 2 conditionals. The first is the the one that will redirect logged in user away from the login page. And the other one is to redirect non logged in user to the login page.

// add a redirect for logged out user
add_action('template_redirect', 'redirect_user');

function redirect_user(){
    global $current_user;
    if (is_page('login-page-for-non-logged-in-user') && is_user_logged_in()){
        $return_url = get_bloginfo('url');
    // this part is untested
    if (!is_page('login-page-for-non-logged-in-user') && !is_user_logged_in()){
        $return_url = get_bloginfo('url');
    // end of untested part
  • Please don't just dump your code, edit and add some explanation how this code might work. Commented Jan 20, 2015 at 9:06
  • Updated the answer. Thank you for the notice Mayeenul
    – ifdion
    Commented Jan 20, 2015 at 10:10
  • @ifdion, it still says This webpage has a redirect loop. Commented Jan 27, 2015 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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