Reputation: 4557
I am a newbie to wordpress
. I am currently working on registration and login. I have a page restrict url let http://xyz.com/abc
. Login/registration is required for this url.
I need that when a user register or login then it should be redirected on this previous url.
In login I have added the following hook :
a
add_filter('login_redirect', 'redirect_previous_page', 10);
function redirect_previous_page(){
global $user;
$request = $_SERVER["HTTP_REFERER"];
if ( in_array( $user->roles[0], array( 'administrator') ) ) {
return admin_url();
return $redirect_to;
} elseif ( in_array( $user->roles[0], array( 'subscriber') ) ) {
return $request;
return $redirect_to;
}
}
It is working for me, but I am not getting how can I redirect on this url after successful registration. I have registration link on the login page
Upvotes: 4
Views: 21584
Reputation: 336
I need that when a user register or login then it should be redirected on this previous url.
If you don`t need permanent redirect for some page you can use redirect in wp_login_url()
// current page with get parameters
$redirect_after_login = home_url( add_query_arg( null, null ) );
// or just
$redirect_after_login = get_the_permalink();
$link_to_login = wp_login_url( $redirect_after_login );
Than you can use this link in wp_safe_redirect()
or just echo somewhere
And here is the corrected code for the redirect after login:
add_filter( 'login_redirect', 'redirect_previous_page', 10, 1 );
function redirect_previous_page( $redirect_to ) {
// don't change url if current user is admin or if user inside admin page
if ( is_admin() || current_user_can( 'administrator' ) ) {
return $redirect_to;
}
// also, we can check is current user has some role
// if (current_user_can( 'subscriber' ))
// change redirect url to previus page for non-administrators
$redirect_to= wp_get_referer();
// referer can return 'false' so add fallback
return $redirect_to ? $redirect_to : home_url();
}
P.S. Unfortunately, no one wrote about the two "returns". The second "return" don`t send because is unattainable
Upvotes: 0
Reputation: 7094
As mentioned in the docs, you can use: <?php wp_get_referer() ?>
to get the last URL visited by user, before logout or after login.
Upvotes: 10
Reputation: 1574
if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
add_filter('login_redirect', 'my_login_redirect', 10, 3);
function my_login_redirect() {
$location = $_SERVER['HTTP_REFERER'];
wp_safe_redirect($location);
exit();
}
}
Upvotes: 9
Reputation: 314
This is rough way but, you can create $_SESSION['your_registration_referrer']
paste there your $_SERVER["HTTP_REFERER"]
and after registration redirect to this url.
Upvotes: 0