View Feed
group-icon
Coffee Room
Discuss anything here - everything that you wish to discuss with fellow engineers.
12894 Members
Join this group to post and comment.
Lavkush Tari
Lavkush Tari • Sep 30, 2018

How to redirect user to previous accessed page after successful login/register in word press

hi, i am using word press to make one site, so i want one functionality in which if user go to suppose blog page mysitename/blog/ he will be redirected to login page say mysitename/login/ and after successfull login/ register the person should be redirected to previous page that is mysitename/blog/ and this should be dynamic for every page i want.

Currenlty i have tried using 

if ( !is_user_logged_in() ) {

header("location:mysitename/login/");

}

in blog page which redirects user to login page

but i dont know how to redirect them to previous accessed page.

any help will be appreciated

Kaustubh Katdare
Kaustubh Katdare • Sep 30, 2018

@Lavkush - If the login happens on some other page than the current page, you will have to store the HTTP REFERER in cache or database temporarily. WordPress has wp_get_referer() function which will give you the page that referred. 

You could then simply make use of: wp_safe_redirect( wp_get_referer() );

Hope this helps. 

Share this content on your social channels -