2

I need a redirection for all not logged-in users on my WordPress site.

All of them should every time be redirected to the login site. So that nobody without a login can access the site. Important is, I made this redirection because I have an API that also needs to have access to the site if I would do this with .htaccess the API hadn't have any access to the information.

I used the following PHP code:

add_action('template_redirect','woo_check_loggedin');
function woo_check_loggedin(){

      if(!is_user_logged_in() && !is_page(lost-password) ){
          wp_redirect("https://example.com/wp-login.php");
          exit;
      }
 
   }

But this only works, when I go to "example.com". When I enter directly the URL "example.com/shop" you can still visit the site. How can I avoid this?

Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • No. I just need, that every site is blocked except for the lost-password site and the login site. Should I write instead: `is_page("https://www.example.com/lost-password")` – Luca Mezger Feb 05 '22 at 11:11

1 Answers1

2

You could use the request property of the wp global variable and wp_login_url function.

add_action('template_redirect', 'woo_check_loggedin');

function woo_check_loggedin()
{
    global $wp;

    if (
        !is_user_logged_in() 
        && 
        'my-account/lost-password' != $wp->request
       ) 
      {
        wp_safe_redirect(wp_login_url(get_permalink()));
        exit;
      }
}

This answer has been tested on woo 6.1 and works!

Related answers for redirection on Wooommerce:

Ruvee
  • 8,611
  • 4
  • 18
  • 44