how to redirect to login page and back again to requested link in wordpress

Viewed 232

I try to everyone come to a post is not login, go to wp-login and after login back to the link requested. cheers!

this is the codes I tried:

<?php
$redirect = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
if (!is_user_logged_in()) {
    wp_redirect( wp_login_url( $redirect ) );
    exit();
}
?>

and try too:

<?php
if (!is_user_logged_in() ) {
wp_redirect( '/wp-login.php' . '?redirect_to=' . $_SERVER["REQUEST_URI"] );
exit;
}
?>

the URL when landing on wp-login is correct with all link (path) requested, but after click in Login button the user don't come back to the URL and go to the website main page for subscribers.

1 Answers

To get the current URL in WordPress we can get the current request from the global $wp object and append it to the site url using add_query_arg(). We can use the result in the redirect_to parameter of wp_login_url() function:

wp_login_url( site_url( add_query_arg( array(), $wp->request ) ) );
Related