I have created a custom login page, different from the default login page. The custom login page is working flawlessly without any errors and redirects after login to a specified page.
However, I need to prevent access to this login page when users are logged in to wordpress and for any reason attempt to view the login page again. The user should be redirected to the home page or any other page I specify. I have used the get_queried_object() function to return the page object's post title element ('Login' in this use case).
The conditional check that should force a redirect when the $page_title = 'Login' as shown in code below does nothing as I can still access the login page even when I am signed into the site.
function redirect_login_page() {
$page_object = get_queried_object();
$page_title = get_queried_object()->post_title;
$login_page = home_url( '/login/' );
$home_page = home_url();
$nf_page = home_url('404');
$page_viewed = basename($_SERVER['REQUEST_URI']);
if (!is_user_logged_in() ) {
if( $page_viewed == "wp-login.php" && $_SERVER['REQUEST_METHOD'] == 'GET') {
wp_redirect($login_page);
exit;
}
}
else
{
if( ($page_viewed == "wp-login.php" or $page_viewed == "login.php" OR $page_title == 'Login') && $_SERVER['REQUEST_METHOD'] == 'GET') {
wp_redirect($home_page);
exit;
}
}
}
add_action('init','redirect_login_page');
How may this redirect be enforced for already logged in users.