I have a WordPress site where some/most of the pages can be viewed by anyone (not logged in). However a user can request to have their own private page, so I set up a page that can only be accessed by that specific person and then email the URL to them. They click on the URL in the email and are sent their page with a login link. Once login is successful I want the user to arrive back at their private page, but currently they just end up at their profile page.
How can I redirect the user to their private page after login?
I have tried so many different bits of code, but none have worked for this situation.
My current code is below. But this just sends the user back to the login page (even though login was successful).
// Function to redirect after login
add_filter('login_redirect', 'redirect_previous_page', 10, 1);
function redirect_previous_page( $redirect_to ){
global $user;
$request = $_SERVER["HTTP_REFERER"];
if ( in_array( $user->roles[0], array( 'administrator') ) ) {
return admin_url();
} elseif ( in_array( $user->roles[0], array( 'subscriber') ) ) {
return $request;
}
return $redirect_to;
}