您的代码片段应该可以正常工作。
首先,您的自定义登录表单可能不尊重redirect_to. wp-login.php 是的,但你必须发送redirect_to 的参数wp-login.php 表单提交。显示登录表单的代码。
你需要小心使用wp_redirect. 它通过发送标题来工作:
<?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);
}
因此,如果部分页面已经加载,而您没有使用
output buffering, 这行不通。
Headers already sent 还有所有的生意。
如果是这样的话,您最好只显示一条带有登录表单链接的消息,或者显示表单本身(例如。wp_login_form).
其次,你应该随时打电话exit 或die 使用后wp_redirect 这将导致PHP脚本(例如WordPress)的执行完成,并发送头和bail。否则,页面下方的内容可能会杀死重定向标头。
<?php
wp_redirect(site_url(\'wp-login.php\'));
exit;
最后,如果要在
redirect_to URL您应该包括协议。
您也可以使用$_SERVER[\'REQUEST_URI\'].
<?php
$url = add_query_arg(\'redirect_to\', $_SERVER[\'REQUEST_URI\'], site_url(\'wp-login.php\'));
wp_redirect($url);
exit;