Scenario: if user not login, user redirect to customize login page and redirect again to destination page after login. I don’t use a function or plugin.
This code to restriction page:
if (!is_user_logged_in()){ wp_redirect( get_option('home') . '?redirect_to=' . esc_url($_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]) );
}
successfully to user login but in login page the URL change to ?page=login
and can’t get URL redirect to destination page. How to make it? Anyone could help, please?
I did something similar recently.
1. If the user is not logged in I captured the desired/destination page’s URL and added it as a query arg to the login page’s URL.
2. Redirect the user to the login page.
function wpa_59205_redirect(){
global $post;
if ( ! is_user_logged_in() ) {
// this will tack on the current page's url as a query arg for the login page's url
$redirect = add_query_arg( 'redirect_to', get_permalink( $post->ID ), $url_of_your_login_page_here );
// redirect to the login page
wp_redirect( $redirect );
exit();
}
}
add_action( 'template_redirect', 'wpa_59205_redirect' );
3. Then you can filter the URL that the user is redirected to after login, using the login_redirect
filter. Simply check for the presence of your previously added query var:
function wpa_59205_login_redirect( $redirect_to ){
if( isset( $_REQUEST['redirect_to'] ) ) {
return $_REQUEST['redirect_to'];
} else {
return $redirect_to;
}
}
add_filter( 'login_redirect', 'wpa_59205_login_redirect');
I did this with a WooCommerce login page, so I was filtering their proprietary login redirect filter, but login_redirect
is the WP default version of the same so I think it should work, but haven’t tested it.