如何在wordpress中保留会话变量? [英] How do I retain session variables in wordpress?

查看:74
本文介绍了如何在wordpress中保留会话变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在 Wordpress 页面模板中开发自定义仪表板,但从未调用过 get_header 或 get_footer,而且我遇到了 SESSION 变量的问题.

I have been developing a custom dashboard inside a Wordpress page template without ever calling get_header or get_footer and I have been experiencing issues with SESSION variables.

似乎是随机保留/删除它们.

It seems to be randomly keeping/deleting them.

这是我非常简单的代码片段:

Here is my very simple code snippet:

<?php
session_start();

print_r($_SESSION);

$_SESSION['test'] = 'test';

?>

这个小片段应该在第一次尝试时打印一个空数组,然后打印测试变量.

This small snippet should print an empty array on the first try and the test variable after that.

相反,它的作用是以随机间隔打印变量.刷新页面 20 次~4 次可以看到变量,其余 16 次是空的.

Instead what it does is print the variable on random intervals. By refreshing the page 20 times ~4 of the you can see the variables and the rest 16 it's empty.

有没有办法防止这种情况发生?

Is there a way to prevent this?

推荐答案

要设置会话,您必须确保尚未设置标题,并且还包括 session_write_close() 否则一些回送功能在 WordPress 中将失败.两个引用的答案都没有提到关于 session_write_close 的这个小花絮.

To set a session you have to make sure headers haven't been set, and also include session_write_close() otherwise some loopback functions in WordPress will fail. Neither of the referenced answers mention this little tidbit about the session_write_close.

function dd_register_session(){
    if(!session_id() && !headers_sent()) {
        session_start();
        session_write_close();
    }
}
add_action('after_setup_theme','dd_register_session', 1);

add_action('wp_logout', 'end_session');
add_action('wp_login', 'end_session');
add_action('end_session_action', 'end_session');

function end_session() {
    session_destroy ();
}

这篇关于如何在wordpress中保留会话变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆