允许登录用户查看页面,否则将发送到登录屏幕,然后重定向回页面

时间:2019-10-30 作者:Thomas Thai

我有一个Wordpress页面,page\\u id=19366。我只希望登录用户查看此页面。如果用户未登录,请将其发送到登录页面,然后将其重定向回id为19366的页面。

在研究了十几种不同的搜索潜在解决方案后,最接近的解决方案是下面的一种。不幸的是,它只重定向到登录页面,但在用户登录后不会再次重定向到引用页面(id 19366)。如果用户已登录,则页面显示良好。我还尝试了第二种解决方案,但也没有成功。

// Solution 1: Restrict access to specific pages
add_action( \'template_redirect\', function() {

        // Get global post
        global $post;
        $where_from = $_SERVER["HTTP_REFERER"];

        // Prevent access to page with ID of 19366 and all children of this page
        $page_id = 19366;
        if ( is_page() && ( $post->post_parent == $page_id || is_page( $page_id ) ) ) {

                // Set redirect to true by default
                $redirect = true;

                // If logged in do not redirect
                // You can/should place additional checks here based on user roles or user meta
                if ( is_user_logged_in() ) {
                        $redirect = false;
                }

                // Redirect people without access to login page
                if ( $redirect ) {


                        function my_login_redirect( $redirect_to, $request, $user ) {
                                $redirect_to = $where_from;
                                return $redirect_to;
                        }

                        add_filter( \'login_redirect\', \'my_login_redirect\', 10, 3 );

                        wp_redirect( esc_url( wp_login_url() ), 307 );
                        exit;
                }


        }

} );
<小时>
// Solution 2
function my_login_redirect( $redirect_to, $request, $user ) {

        // Get global post
        global $post;
        $where_from = $_SERVER["HTTP_REFERER"];

        // Prevent access to page with ID of 2 and all children of this page
        $page_id = 19366; // Happy Volleydays Tournament Poll. Page ID = 19366
        //if ( is_page() && ( $post->post_parent == $page_id || is_page( $page_id ) ) ) {
        if ( is_page( $page_id ) && ! is_user_logged_in() ) {
                return $request;
        }
        return $redirect_to;

}
add_filter( \'login_redirect\', \'my_login_redirect\', 10, 3 );

1 个回复
最合适的回答,由SO网友:ChristopherJones 整理而成

你可以通过wp_login_url() 登录时重定向到的URL。https://codex.wordpress.org/Function_Reference/wp_login_url

如果您使用了第一种解决方案exit;, 你有wp_redirect() 呼叫您可以将该行替换为以下内容

wp_redirect( esc_url( wp_login_url(get_permalink($page_id)) ), 307 );
我不会使用你的第二种解决方案。

希望有帮助!!

相关推荐

在Cloudflare之后无法访问wp-admin和wp-login.php

我有以下几点.htaccess 限制访问的规则wp-admin 和wp-login.php 本地通过SSH动态转发:Order Deny,Allow Deny from all Allow from 127.0.0.1 但是,安装Cloudflare后,我无法访问/wp-admin 和wp-login.php 不再之前,我在我的access.log:127.0.0.1 - - [20/Jun/2019:06:30:12 +0000] \"POST /wp-admin/admin-