I have just installed WordPress locally in my computer and run the website successfully. I want to achieve following: when logged-in user tries to access wp-login.php or register page, it should be automatically redirected to home page.
I have spent several hours on web, but could no come up with solution neither was I able to find appropriate WordPress plugin.
My question is: why does WordPress function this way? how can we change this behavior as natively as simply as possible?
Thank you
I have just installed WordPress locally in my computer and run the website successfully. I want to achieve following: when logged-in user tries to access wp-login.php or register page, it should be automatically redirected to home page.
I have spent several hours on web, but could no come up with solution neither was I able to find appropriate WordPress plugin.
My question is: why does WordPress function this way? how can we change this behavior as natively as simply as possible?
Thank you
Share Improve this question edited Feb 27, 2021 at 17:47 Tornike Shavishvili asked Feb 27, 2021 at 16:48 Tornike ShavishviliTornike Shavishvili 1235 bronze badges2 Answers
Reset to default 1You can check the current page being loaded through the $pagenow global variable. Both login and registration is handled through wp-login.php. Adding this to the functions.php of your theme should work:
<?php
add_action('init', function () {
if ($GLOBALS['pagenow'] === 'wp-login.php' && is_user_logged_in() && (!isset($_GET['action']) || $_GET['action'] !== 'logout')) {
wp_redirect(home_url());
exit;
}
});
EDIT: Added a check to allow logging out and clarified where to put this code.
i modified @Patriot code.
I was able to achieve desired functionality with following code:
I added this code to \wp-includes\functions.php
at the and of file.
It not as clean is i wished, but it works.
If someone sees any possible issues with this approach, please inform us
add_action('init', function() {
if ($GLOBALS['pagenow'] === 'wp-login.php' && is_user_logged_in()) {
$defLoginPageActions = array(
//'confirm_admin_email',
//'postpass',
'logout',
//'lostpassword',
//'retrievepassword',
//'resetpass',
//'rp',
//'register',
//'checkemail',
//'confirmaction',
//'login',
WP_Recovery_Mode_Link_Service::LOGIN_ACTION_ENTERED,
);
$loginPageAction = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : '';
if(!in_array( $loginPageAction, $defLoginPageActions)){
wp_redirect(home_url());
exit;
}
}
});