Best practice for global redirect for non-logged in users?

My site is Sage11 and Woocommerce. It needs to ‘require’ users to be logged in, so I’m thinking that the best solution would be for me to just redirect any non-logged-in users to my-account which is part of Woo, that way I can control all the templating for the various login/register/forgotten password pages.

How can I achieve this with Sage11? Would I need to use routing and set up some middleware to check if user is logged in?

Much appreciated

Have you considered the template_redirect hook?

1 Like

Yes that works… just dropping my function in here for my own future reference :wink:

function redirect_not_logged_in()
{
    if(is_login()){
        return;
    }
    if (! is_user_logged_in() && !is_page(wc_get_page_id('myaccount'))) {
        $url = add_query_arg(
            'redirect_to',
            $_SERVER['REQUEST_URI'],
            site_url('/my-account/') // your my account url
        );
        wp_redirect(site_url($url));
        exit;
    }
}
add_action('template_redirect', '\App\redirect_not_logged_in');
2 Likes

No need to call site_url() twice :wink:

wp_redirect($url); // Remove the extra site_url() wrapper
1 Like