WordPress开发函数auth_redirect()
WordPress开发函数auth_redirect(),检查用户是否已登录,如果没有,则将他们重定向到登录页面。
用法:
auth_redirect()
描述:
当从页面调用这段代码时,它会检查查看该页面的用户是否已登录。如果用户没有登录,他们将被重定向到登录页面。用户被重定向到这样一种方式,在登录时,他们将被直接发送到他们最初试图访问的页面。
来源:
文件: wp-includes/pluggable.php
function auth_redirect() {
$secure = ( is_ssl() || force_ssl_admin() );
/**
* Filters whether to use a secure authentication redirect.
*
* @since 3.1.0
*
* @param bool $secure Whether to use a secure authentication redirect. Default false.
*/
$secure = apply_filters( ‘secure_auth_redirect’, $secure );
// If https is required and request is http, redirect.
if ( $secure && ! is_ssl() && false !== strpos( $_SERVER[‘REQUEST_URI’], ‘wp-admin’ ) ) {
if ( 0 === strpos( $_SERVER[‘REQUEST_URI’], ‘http’ ) ) {
wp_redirect( set_url_scheme( $_SERVER[‘REQUEST_URI’], ‘https’ ) );
exit;
} else {
wp_redirect( ‘https://’ . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘REQUEST_URI’] );
exit;
}
}
/**
* Filters the authentication redirect scheme.
*
* @since 2.9.0
*
* @param string $scheme Authentication redirect scheme. Default empty.
*/
$scheme = apply_filters( ‘auth_redirect_scheme’, ” );
$user_id = wp_validate_auth_cookie( ”, $scheme );
if ( $user_id ) {
/**
* Fires before the authentication redirect.
*
* @since 2.8.0
*
* @param int $user_id User ID.
*/
do_action( ‘auth_redirect’, $user_id );
// If the user wants ssl but the session is not ssl, redirect.
if ( ! $secure && get_user_option( ‘use_ssl’, $user_id ) && false !== strpos( $_SERVER[‘REQUEST_URI’], ‘wp-admin’ ) ) {
if ( 0 === strpos( $_SERVER[‘REQUEST_URI’], ‘http’ ) ) {
wp_redirect( set_url_scheme( $_SERVER[‘REQUEST_URI’], ‘https’ ) );
exit;
} else {
wp_redirect( ‘https://’ . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘REQUEST_URI’] );
exit;
}
}
return; // The cookie is good, so we’re done.
}
// The cookie is no good, so force login.
nocache_headers();
$redirect = ( strpos( $_SERVER[‘REQUEST_URI’], ‘/options.php’ ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( ‘http://’ . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘REQUEST_URI’] );
$login_url = wp_login_url( $redirect, true );
wp_redirect( $login_url );
exit;
}
更新日志:
用户贡献的笔记
(Jeroen Rotty 3年前贡献)
要求用户登录才能查看页面:
if ( !is_user_logged_in() ) {
auth_redirect();
}
(2个月前,由awayshops贡献)
这段代码有个错误。参数不保留。如果用户最初试图加载的页面,需要的参数,在成功登录后重定向,页面加载不需要参数。