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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You 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.
Method 2
i modified @Patriot code.
I was able to achieve desired functionality with following code:
I added this code to wp-includesfunctions.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;
}
}
});
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0