php – WordPress redirect redirecting too many times or not at all

Question

I am new to WordPress. I am trying to simply redirect users to a login page if they go to the account page without being logged in.

I first tried adding this code to the functions.php code:

add_action('template_redirect', 'redirect_if_user_not_logged_in' );

function redirect_if_user_not_logged_in() && is_page('example.com/account') {

if ( !is_user_logged_in()) {

      wp_redirect('example.com/login'); 
   
   exit;
   }
}

This ultimately resulted in nothing. At all happening. I tried the hook ‘admin_init’ as well which made no difference.

I tried removing the conditional statement about the current page and changed the code to simply:

add_action('template_redirect', 'redirect_if_user_not_logged_in' );

function redirect_if_user_not_logged_in() {

if ( !is_user_logged_in()) {

      wp_redirect('example.com/login'); 
   
   exit;
   }
}

This resulted in the “ERR_TOO_MANY_REDIRECTS” error on both Chrome and Microsoft Edge. I would’ve thought that this would just redirect once but it appears that it gets caught in a loop.

Again, I tried this with several different hooks as well as ‘init’ and ‘admin_init’.

The code is located just below the <?php of functions.php.

I’m not sure what I am doing wrong here. Perhaps I am putting this code in the wrong file or I need to adjust the add_action and hook or use remove_action somewhere else. Please lend me a hand.

0
thisissparzo 4 months 2022-01-20T03:25:55-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse