WordPress函数:auth_redirect 登录验证后跳转

江河/ 2023年07月23日/ WordPress/ 浏览 903

函数原型:


auth_redirect()


检查用户是否已登录,如果未登录,则会将其重定向到登录页面。


当从页面调用此代码时,它会检查查看该页面的用户是否已登录。


如果用户未登录,则会将其重定向到登录页面。用户被重定向的方式是,登录后,他们将被直接发送到他们最初试图访问的页面。


函数源码:


function auth_redirect() {
	$secure = ( is_ssl() || force_ssl_admin() );

	$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;
		}
	}

	$scheme = apply_filters( 'auth_redirect_scheme', '' );

	$user_id = wp_validate_auth_cookie( '', $scheme );
	if ( $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;
}


包含钩子:


do_action( 'auth_redirect', int $user_id )

apply_filters( 'auth_redirect_scheme', string $scheme )

apply_filters( 'secure_auth_redirect', bool $secure )


使用举例:


if ( !is_user_logged_in() ) {
   auth_redirect();
}


发表评论

暂无评论,抢个沙发...

客服 工单