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;
}
If you are using a login link on the homepage to go to the login page, then use the following code,
echo wp_login_url( $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] );
If you are using a custom form on the frontpage, then inside the , make sure you fill in a hidden field with the url to redirect
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; ?>" />
And if you are using wp_login_form() to generate the form, then follow the below code, for more information checkout this page, wp_login_form
$args = array(
'echo' => true,
'redirect' => site_url( $_SERVER['REQUEST_URI'] ),
'form_id' => 'loginform',
'label_username' => __( 'Username' ),
'label_password' => __( 'Password' ),
'label_remember' => __( 'Remember Me' ),
'label_log_in' => __( 'Log In' ),
'id_username' => 'user_login',
'id_password' => 'user_pass',
'id_remember' => 'rememberme',
'id_submit' => 'wp-submit',
'remember' => true,
'value_username' => NULL,
'value_remember' => false );
wp_login_form( $args );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With