如果用户未登录,则显示自定义模板,而不考虑正在查看的页面

时间:2014-11-25 作者:David Gard

我的任务是创建一个WordPress站点,订阅者(由管理员注册)不知道后端。

我还必须这样做,在导航到任何页面时,如果用户没有登录,就会显示一个登录表单。登录后,应显示用户试图查看的页面。

我有以下代码whcih检测用户是否登录并向他们显示登录页面,但不幸的是,由于这需要重定向,因此显然无法将用户重定向到他们最初想要去的地方。

我想做的是检测usre是否已登录,以及它们是否未覆盖通常用于自定义的模板login.php 模板,类似于404模板的显示方式。

要做到这一点,我想我需要以某种方式连接到模板层次结构,并覆盖通常的模板,但我不确定具体如何实现这一点,并将听取任何提示。

这是我目前得到的信息,如果用户未登录,它会将用户重定向到特定页面(虽然很接近,但并不完美)-

/**
 * Redirect the user to the \'please login\' page if they are not logged in
 */
add_action(\'wp\', \'djg_check_login\');
function djg_check_login(){

    $scheme = (is_ssl()) ? \'https\' : \'http\';

    /** Construct the URL of the page the user is trying to view */
    $url = sprintf(
        \'%1$s://%2$s%3$s\',
        $scheme,                    /** %1$s - The request shceme (http|https) */
        $_SERVER[\'SERVER_NAME\'],    /** %2$s - The server name */
        $_SERVER[\'REQUEST_URI\']     /** $3$s - The request URI */
    );

    /** List the pages that are authorised for non-logged in users */
    $authorised_pages = array(
        get_site_url().\'/login/\',
        get_site_url().\'/wp-login.php\'
    );

    /** Ensure that the user is actually NOT logged in */
    if(!is_user_logged_in()) :

        /** Ensure we are not trying to view an $authorised page (to avoid a loop) */
        if(!in_array($url, $authorised_pages)) :

            /** Redirect the user and exit */
            wp_safe_redirect(get_page_link(7));
            exit;

        endif;

    endif;

}

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

事实证明,使用template_include 过滤器-

/**
 * Override the standard WordPress template with the \'please login\' template if the current user is not logged in
 */
add_filter(\'template_include\', \'portfolio_page_template\', 99);
function portfolio_page_template($template){

    /** List the pages that are authorised for non-logged in users */
    $authorised_pages = array(
        get_site_url().\'/login/\',
        get_site_url().\'/wp-login.php\'
    );

    /** Ensure that the user is actually NOT logged in */
    if(!is_user_logged_in()) :

        /** Ensure we are not trying to view an $authorised page (to avoid a loop) */
        if(!in_array($url, $authorised_pages)) :

            /** Setup the new template */
            $new_template = locate_template(array(\'login-page.php\'));
            if($new_template !== \'\') :
                return $new_template ;
            endif;

        endif;

    endif;

    return $template;

}

结束

相关推荐

强制[WordPress_Social_LOGIN]快捷代码显示其嵌入位置

这个WordPress Social Login 插件包含[wordpress_social_login] 可以在帖子和页面中使用的短代码。问题是,无论我把它放在帖子正文的什么地方,它总是作为页面上的第一件事呈现。我使用的是突出的主题,我一直在查看一个名为wsl_render_login_form() 它似乎呈现了它,但不清楚它是如何首先将其放置在页面上的。如何在实际放置的位置进行短代码渲染?看起来这应该是默认值,但令人恼火的是事实并非如此。