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.
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: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.Your snippet should work fine.
First off, your custom login form may not respect
redirect_to
.wp-login.php
does, but you’ll have to send theredirect_to
argument to thewp-login.php
form submission as well. Show the code for your login form.You need to be careful how you use
wp_redirect
. It works by sending headers:So if parts of your pages have already loaded and you’re not using output buffering, it won’t work.
Headers already sent
and all that business.If that’s the case you might be better off just showing a message with a link to the login form or show the form itself (eg.
wp_login_form
).Second, you should always call
exit
ordie
after usingwp_redirect
this causes the execution of the PHP script (eg. WordPress) to finish, send headers and bail. Otherwise things further down the page may kill your redirection headers.Finally, if you are going to include the host in your
redirect_to
URL you should include the protocol.You can also just use
$_SERVER['REQUEST_URI']
.wp_redirect: http://codex.wordpress.org/Function_Reference/wp_redirect
wp_login_url: http://codex.wordpress.org/Function_Reference/wp_login_url