Therefore, all of the rewrites and URLs will be relative to these URLs.
Handling the Referer Capture
When someone comes to one of the pages on your site, you want to capture that original request and add it as a redirect_to=
query arg. Then you can send them to the login page.
add_action( 'wp', 'redirect_to_login_if_unauthorized', 3 );
function redirect_to_login_if_unauthorized( WP $wp_environment ) {
if ( is_user_logged_in() ) {
return;
}
if ( $wp_environment->request ) {
$request = home_url( add_query_arg( array(), $wp_environment->request ) );
} else {
$request = home_url();
}
$redirect = home_url() . '/wp-login.php?redirect_to=' . $request;
wp_redirect( $redirect );
die();
}
How it Works
The event wp
fires in wp-includes/class-wp.php
. It passes the object instance of the WordPress environment setup. Here is the code from WordPress Core:
do_action_ref_array( 'wp', array( &$this ) );
This environment object has a property that we want called request
. That property has the URL request (minus the blog’s home URL).
If the $wp_environment->request
has a value, we’ll add it to the home URL as a query arg; else, we just want the home URL. Now we have the referer.
Next, you create the redirect URL, which has the path to the login page and the redirect_to
query arg.
An Example
Let’s say you have a post called Why I Love WordPress
and the path to that post is http://example.com/blog/why-i-love-wordpress
.
The value in the $request
would be:
http://example.com/blog/why-i-love-wordpress
and the redirect URL would be:
http://example.com/blog/wp-login.php?redirect_to=http://example.com/why-i-love-wordpress
Upon logging in, the user is then redirected to the original page request.
Tip – Handle Logout Too
You’ll want to think about the pathing after a user logs out and then build a proper request to it too.