I'm creating a website for a client https://www.virtualflooringco.com.au and it is a website that is behind password due to franchise conditions, but the page located at /login can be accessed by already logged in users.
I want to force visitors that go to the login page and that are already logged in to be redirected to /home. Currently I have a button on the login page that if they are already logged in, to click and it'll take them to that /home link, but I'm looking for a more professional solution.
I have looked through stackoverflow and can't seem to find anything that related to what I'm trying to do.
Any help would be greatly appreciated.
CodePudding user response:
Use an authentication to your login function. When the user submits their user details, the PHP code will compare the submitted data to your database.
If match found, then it sets the users logged-in session. In this authentication code, it preserves the user id
in a PHP session
.
After of authentication, the PHP $_SESSION
super global variable will contain the user id
. Example, $_SESSION[“user_id”] is set to manage the logged-in session. It will remain until log out or quit from the browser.
And in logout, unset all the session variables using PHP unset() function.
CodePudding user response:
This should do it
function redirect_to_home() {
// Check if we are logedin and we are on login page
if(!is_admin() && is_page('login') && is_user_logged_in()) {
//redirect to homepage if we try to access login page.
wp_redirect(home_url().'/home');
exit();
}
}
add_action('template_redirect', 'redirect_to_home');