I work for a group of newspapers here in Iowa. We recently started moving these sites to WordPress. Site visitors must be logged in to view stories. They can see all the stories on the front page, but when they click through to a single story, they see a login form in place of the post/story content.
I needed to redirect users back to the page they were viewing after logging in. So, if a user was viewing a story called “Look at me now”, they’d need to be redirected back to that story after logging in.
To achieve this redirect to previous page after login, add the following code to the functions.php file for your theme:
I looked at a number of plugins to do this, but none seemed to offer this functionality.
A bit of searching on Google yielded this post at Taproot Creative. I modified the code on that post to set the redirect location to the referring page, and that was it!
Now users are redirected back to the story/post they originated from.
If you use a functionality plugin, which you really should, it’d make an ideal home for this snippet of code. So if you can, drop it in a functionality plugin instead of the
functions.php file for your theme.
This Doesn’t Work!
For the code above to work, your login form must be embedded in one of you theme’s templates, or in a post or page.
If you’re providing users a “Login” button that takes them to the default login page (wp-login.php), this won’t work for you, users will be sent to the WordPress dashboard instead of the page they were at before hitting wp-login.php.
If the code above doesn’t work (ie: users are logging in at wp-login.php), the code below will allow you to define a page to redirect users to after login:
The example above will redirect users (including administrators) to /members/, and uses the home_url() WordPress function. So, if I were using this here, users would be redirected to https://longren.io/about/.
If you want to redirect users based on their role, like redirecting Administrators to the dashboard like normal, check out the example provided in the login_redirect filter documentation.
Well, now what?
Work with Me
I'm available for hire and always taking new clients, big and small. Got a project or an idea you'd like to discuss? Startup plan but no developer to make it happen? Just get in touch, I'd love to see if I can help you out!