Search code examples
phpwordpresshttp-redirectwoocommercewoocommerce-theming

WooCommerce how to perform a redirection for not logged in users


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?


Solution

  • 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: