繁体   English   中英

WordPress is_page_template 无法正常工作初始化操作

[英]WordPress is_page_template not working right init action

我将上面的代码放入主题的函数文件中。 当请求另一个不使用模板 page_forms 的页面时,我执行此代码以注销用户“信使”。

但是,当我访问某个使用此模板的页面时,我被重定向到主页并且会话已关闭。 这让我相信 is_page_template 语句无法正常工作。

有没有人有任何提示?

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' 的问题。 此更改使用户信使在 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');

现在的问题是,在 page-forms.php 上使用 Messenger 登录后,注销会自动发生,而无需遵守函数的第二个语句,其中模板不需要是 page-forms.php 来触发注销(无需重定向到主页——疯了!)。

当我评论函数 wp_clear_auth_cookie 时,问题就停止了。 但是这个功能失去了你的海豚。

该函数is_page_template工作正常,只要确保您使用的是page_form模板的正确路径,如果该模板位于任何文件夹中,例如folder/page-form.php那么您必须在主题文件夹之后使用该完整路径,假设您模板在templates文件夹内,那么你必须需要在is_page_template函数中传递templates/page-forms.php is_page_template

如果这对您有帮助,请告诉我

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM