Hi– thanks for using Force Login!
How can I redirect users to the URL they try to reach without losing the anchor?
Unfortunately, it’s not possible to know the anchor since the hash (the string including the #) never gets passed to the server, it is solely a behavioral property of the browser.
You can use Javascript to get the hash value, but then the page has loaded to run Javascript instead of having the PHP (server-side) redirect visitors to the login screen.
—
However, you may change the url passed to the ?redirect_to=
query using the v_forcelogin_redirect
filter. Below is an example of sending visitors trying to visit your “/my-article” page to a specific anchor.
/**
* Set the URL to redirect to on login.
*
* @return string $redirect_url URL to redirect to on login. Must be absolute.
*/
function my_forcelogin_redirect( $redirect_url ) {
if ( is_page('my-article') ) {
$redirect_url = site_url( '/my-article/#subject-3' );
}
return $redirect_url;
}
add_filter( 'v_forcelogin_redirect', 'my_forcelogin_redirect' );
Hi Kevin,
Thanks for your answer!
If I understand, the method you propose me is for only one page with an anchor? If I have multiple pages with anchor, I can’t use this solution because every redirection will be on the page I’ve entered in this function?
Thanks anyway for your help 🙂
The code example using the v_forcelogin_redirect
filter only changes the redirect URL to an anchor link for that one page, is_page('my-article')
, else it defaults to just the page url they tried to visit.
Examples:
If a visitor tried to access /another-page/ they would be redirected to /another-page/ after a successful login.
If a visitor tried to access /my-article/#subject-1 they would be redirected to /my-article/#subject-3 after a successful login.
—
The code example using the v_forcelogin_redirect
filter shows you how you could alter the redirect URL, but like I said before– it’s not possible to know the anchor since the hash (the string including the #) never gets passed to the server.
Thanks Kevin, everything is crystal clear now 🙂
No problem, thanks for using Force Login! 🙂