Php WordPress页面模板在初始化操作时无法正常工作

Php WordPress页面模板在初始化操作时无法正常工作,php,wordpress,Php,Wordpress,我把上面的代码放到我的主题文件中。我编写这段代码是为了在请求另一个不使用模板页面表单的页面时注销用户“messenger” 但是,当我访问一些使用此模板的页面时,我被重定向到主页,会话被关闭。这让我相信is_page_模板语句工作不正常 有人有什么建议吗 function messenger_session(){ $current = wp_get_current_user(); if( isset($current->user_login) && $c

我把上面的代码放到我的主题文件中。我编写这段代码是为了在请求另一个不使用模板页面表单的页面时注销用户“messenger”

但是,当我访问一些使用此模板的页面时,我被重定向到主页,会话被关闭。这让我相信is_page_模板语句工作不正常

有人有什么建议吗

function messenger_session(){

    $current = wp_get_current_user();

    if( isset($current->user_login) && $current->user_login == 'messenger' && !is_page_template('page-forms.php') ):

        $redirect_to = get_home_url();

        wp_logout();
        wp_safe_redirect( $redirect_to );
        exit;

    else:
        return;

    endif;
}
add_action('init','messenger_session');
更新

经过研究,我解决了将'init'从add_action更改为'template_redirect'的问题。此更改会使用户messenger保持登录到page-forms.php

但是,如果需要任何其他模板,第二步是注销该用户。因此,为了实现这一点,我在代码中做了一些更改:

function messenger_login(){

    $current = wp_get_current_user();

    if( is_page_template('page-forms.php') && !isset( $current->user_login ) ) :

        $username = 'messenger';
        $user       = get_user_by( 'login', $username );

        wp_clear_auth_cookie();
        wp_set_current_user( $user->ID );
        wp_set_auth_cookie( $user->ID );
        return;

    elseif( !is_page_template('page-forms.php') && isset( $current->user_login ) && $current->user_login == 'messenger' ):

        $redirect_to = get_home_url();

        wp_clear_auth_cookie();
        wp_safe_redirect( $redirect_to );
        die;

    else:
        // do nothing

    endif;
}

add_action('template_redirect','messenger_login');
现在的问题是,在messenger登录page-forms.php之后,注销会自动发生,而不考虑函数的第二条语句,在该语句中,模板不需要是page-forms.php就可以启动注销(不重定向到home,这太疯狂了!)


当我对函数wp\u clear\u auth\u cookie进行注释时,问题就停止了。但是该函数会丢失您的权限。

该函数
是页面模板
工作正常,只需确保您使用的是页面表单模板的正确路径。如果该模板位于任何文件夹(如
文件夹/page form.php
中),则必须在主题文件夹后使用该完整路径假设您的模板在
templates
文件夹中,那么您必须传递
templates/page表单。php
中是页面模板
函数


让我知道这是否有助于您

函数写在functions.php主题文件中,page-forms.php是位于主题根文件夹中的模板。在另一种情况下,对该页面的调用工作正常,但使用此函数,而不是。这看起来很奇怪,因为相同的代码在默认WP主题下为我工作,您能否尝试将
init
action更新为
WP
action,以帮助您节省时间。但在尝试使用“wp”而不是“init”之后,问题仍然存在。我通过“模板\重定向”更改“init”来解决这个问题。不管怎样,现在我还有第二部分要解决。这一部分是通过更新在原始帖子中提到的。我将通知您接受任何帮助!谢谢