Aleš Sýkora / June 26, 2021 / 0 comments

Redirect non logged users to login page

Post summary: Situation: Website with pages restricted only to logged in users and we do not use toolset content templates but Oxygen Builder. We are hiding the content to the non-logged in users with Oxygen conditionals but we would like to redirect user to the login page instead of displaying login form on every restricted page. Code…

Situation: Website with pages restricted only to logged in users and we do not use toolset content templates but Oxygen Builder. We are hiding the content to the non-logged in users with Oxygen conditionals but we would like to redirect user to the login page instead of displaying login form on every restricted page.

Code snippet for redirection to custom login page:

add_action( 'template_redirect', 'redirect_visitors_to_login' );
function redirect_visitors_to_login( $template ) {
    // if current visitor is not logged-in
    if ( !is_user_logged_in() ) {
        // list of pages to exclude from the redirect
        $excluded_page_ids = array(12, 14, 16, 18);
        // ID of the login page where visitors should be redirected to
        $login_page_id  = 12;
        // if the current page is not among the excluded pages
        if ( !is_page( $excluded_page_ids) ) {
            // redirect to the login page
            wp_redirect( get_permalink($login_page_id) );
        }
    }
    return $template;
}

Please replace 12, 14, 16, & 18 with the actual page IDs of the excluded pages on your website.

Other way – when you are using Toolset Access and Toolset Content templates, is creation of custom content template for the Access Group and use meta redirection in it.

<meta http-equiv="refresh" content="0; url=https://example.com/" />

Change the URL to your login page.

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

0 comments

Share Your Thoughts