I have the following code to redirect users which are logged in and on the homepage:
function add_login_check()
{
if ( is_user_logged_in() && is_page(7) ) {
?>
<script>window.location='/user-area/'</script>
<?php
exit();
}
}
add_action('wp', 'add_login_check');
But I am trying to modify it to only redirect users as they actually login (only to redirect once (as they login)), rather than every time they visit the homepage whilst they are logged in.
I have tried using session as follows:
function add_login_check()
{
if(!isset($_SESSION['didit'])) {
if ( is_user_logged_in() && is_page(7) ) {
?>
<script>window.location='/user-area/'</script>
<?php
exit();
}
$_SESSION['didit'] = true;
}
}
add_action('wp', 'add_login_check');
Also adding session_start();
to the beginning of my theme, but I can’t get it to work 🙁 I’d really appreciate any help, thanks so much!!!
2
Answers
You can achieve the redirect after login using the wp_login action hook instead of relying on sessions. Here’s how you can modify your code to redirect users only once when they log in:
The wp_login action checks if the user has already been redirected by using the user meta field _redirect_done. If not, it redirects the user and sets the flag to true. The wp_logout action clears the redirect flag so that the user can be redirected again upon the next login.
This way, users are only redirected once after logging in, and the flag is reset when they log out.
I think that you can achieve this by altering your code a little bit.
Please try the code like this .
You can also use
is_home()
oris_front_page()
instead of is_page(page_id) that you are currently using as far as you intent to use this codehttps://developer.wordpress.org/reference/functions/is_home/
https://developer.wordpress.org/reference/functions/is_front_page/
I also believe that cookie is a better practice than session variable , because you can alter the cookie life span , from 0 ( browser closes means that cookie is expires from x amount of time).
https://www.php.net/manual/en/reserved.variables.cookies.php
The current code and changes are untested , so please if you test them you can give feedback and i can assist you further. Cheers!