In WordPress, how do I get the “redirect_to” URL argument to include the path & arguments of the original page for redirecting after logging in?

I have a custom folder called /portal/ that takes arguments like /portal/?id=123 or /portal/?id=321 etc.

In the /portal/index.php file I included the following which automatically redirects users to the WP login if the user is not authenticated.

Read More

include_once( $_SERVER[‘DOCUMENT_ROOT’] . ‘/wp-load.php’ );

If not logged in they are automatically redirected to http://www.domain.com/wp-login.php?redirect_to=http%3A%2F%2Fwww.domain.com%2F&reauth=1.

How do I fix the redirect_to argument so it includes the path and arguments? I want the redirect to look like this:

http://www.domain.com/wp-login.php?redirect_to=http%3A%2F%2Fwww.domain.com%2Fportal%2F?id%3D123&reauth=1

This way, once the user logs in, they will be redirected to the page they were trying to access in the first place.

Related posts

Leave a Reply

2 comments

  1. First, including wp-load.php isn’t recommended – Don’t include wp-load, please – for several reasons.

    Presumably you have WordPress configured to require a login, which is why are you are getting a redirect to the login page, and because it is happening directly from your include, you can’t insert any filters to change the redirect before it’s loaded, and using them afterwards is moot because the redirect will have already fired.

    If this was constructed as a plugin it would be loaded by wp-load, and you would have access to the login_url filter, which you can use to add a redirect as in this example: http://trepmal.com/filter_hook/login_url/.

  2. I was able to come up with a hack that checks for the existence of a cookie key begining with wordpress_logged_in_. If the cookie key doesn’t exist then I redirect to the login page to http://www.domai.com/wp-login.php?redirect_to=http%3A%2F%2Fwww.domain.com'.urlencode($_SERVER['REQUEST_URI']).