i'm using this code to redirect not logged users from a specific page to login page
add_action( 'template_redirect', function() {
if ( is_user_logged_in() || ! is_page() ) return;
$restricted = array( 5049 ); // all your restricted pages
if ( in_array( get_queried_object_id(), $restricted ) ) {
wp_redirect( site_url( '/user-account' ) );
exit();
}});
after login users are redirect to their account i want to change this to redirect them to previous page that they visited
My Answer:
You can achieve this by storing the previous page URL in a session variable before redirecting the user to the login page. Then, after the user logs in successfully, you can redirect them back to the stored URL.
Here's an updated version of your code:
php
add_action( 'template_redirect', function() {
if ( is_user_logged_in() || ! is_page() ) return;
$restricted = array( 5049 ); // all your restricted pages
if ( in_array( get_queried_object_id(), $restricted ) ) {
// Store the current page URL in a session variable
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
wp_redirect( site_url( '/user-account' ) );
exit();
}
});
// Redirect users to the previous page after login
add_filter( 'login_redirect', function( $redirect_to, $request, $user ) {
if ( isset( $_SESSION['redirect_to'] ) ) {
$redirect_to = $_SESSION['redirect_to'];
unset( $_SESSION['redirect_to'] );
}
return $redirect_to;
}, 10, 3 );
Make sure to start the session at the beginning of your code by adding `session_start();`. This will allow you to store and retrieve values in the `$_SESSION` superglobal array.
With this code, users will be redirected to the previous page they visited after logging in successfully.
Rate this post
5 of 5 based on 8970 votesComments