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 the redirect_to
argument to the wp-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:
<?php
/**
* Redirects to another page.
*
* @since 1.5.1
* @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
*
* @param string $location The path to redirect to
* @param int $status Status code to use
* @return bool False if $location is not set
*/
function wp_redirect($location, $status = 302) {
global $is_IIS;
$location = apply_filters('wp_redirect', $location, $status);
$status = apply_filters('wp_redirect_status', $status, $location);
if ( !$location ) // allows the wp_redirect filter to cancel a redirect
return false;
$location = wp_sanitize_redirect($location);
if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
status_header($status); // This causes problems on IIS and some FastCGI setups
header("Location: $location", true, $status);
}
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
or die
after using wp_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.
<?php
wp_redirect(site_url('wp-login.php'));
exit;
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']
.
<?php
$url = add_query_arg('redirect_to', $_SERVER['REQUEST_URI'], site_url('wp-login.php'));
wp_redirect($url);
exit;