0

I have integrated custom login form as mentioned here and embed this custom login form to a WordPress page, via shortcode [dm_login_form].

After that I have integrated access control plugin here which allows me to redirect user to login page if not logged in.

I need to redirect user to my custom login page whenever a blog post/page is accessed by a non-authenticated user. It goes into redirect loop if I provide my custom login page URL.

For admin authentication I am using default wp-login.php URL while other users login using custom login page URL.

Code in functions.php for redirection

add_action('template_redirect', 'redirect_user');

function redirect_user(){
    global $current_user;
    if (!is_user_logged_in()){
        $return_url = site_url().'/login';
        wp_redirect($return_url);
        exit();
    }
}

I just need to redirect user to my login page URL if hes not logged in and try to access any page/post. How can I prevent this redirect loop ?

Thanks.

  • add exit; just after wp_redirect($return_url);. – Robert hue Jan 27 '15 at 12:13
  • @Roberthue, question updated. – Slimshadddyyy Jan 27 '15 at 12:15
1

Here is the function to redirect non-users to login page.

function redirect_user() {
  if ( ! is_user_logged_in() && ! is_page( 'login' ) ) {
    $return_url = esc_url( home_url( '/login/' ) );
    wp_redirect( $return_url );
    exit;
  }
}
add_action( 'template_redirect', 'redirect_user' );
  • Using the code, when I try to access contact-us/ page, it goes into redirect loop. – Slimshadddyyy Jan 27 '15 at 12:29
  • 2
    Maybe if ( ! is_user_logged_in() && ! is_page( 'login' ) ) will avoid the redirect loop. – birgire Jan 27 '15 at 13:03
  • @Slimshadddyyy make sure page slug is correct. – Robert hue Jan 27 '15 at 13:21
  • @birgire made changes in code to avoid redirection loop to login page. :) Thanks – Robert hue Jan 27 '15 at 13:24
  • @Roberthue may be plugin WordPress Access Control Settings is redirecting it to default wp-login page, overriding the code. If the defult login url is changed from plugin settings then it goes to redirect loop. – Slimshadddyyy Jan 27 '15 at 13:38

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.