php 如何在插件开发中使用wordpress中的session
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16118817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use session in wordpress in plugin development
提问by Vaibs_Cool
I am new to write a plugin ..I am having a testplugin.php file and a ajax.php file ..
我是编写插件的新手..我有一个 testplugin.php 文件和一个 ajax.php 文件..
My code in testplugin.php is
我在 testplugin.php 中的代码是
global $session;
print_r($abc); //$abc is array of my data ..
$session['arrayImg']=$abc; //saving data in session
echo $session['arrayImg']; //displayin "Array"
And my ajax.php consists of following code
我的 ajax.php 包含以下代码
global $session;
$abc = $session['arrayImg'];
print_r ("abs== ".$abc); //displayin "abs== Array"
And if use session_start();
如果使用 session_start();
I get following error
我收到以下错误
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent
I just want to send array of data from one file of my plugin to another file ...
我只想将数据数组从我插件的一个文件发送到另一个文件...
回答by Shazzad
// On your plugin or themes functions.php
// 在你的插件或主题functions.php
function register_session(){
if( !session_id() )
session_start();
}
add_action('init','register_session');
// To set a SESSION
data -
// 设置SESSION
数据 -
$_SESSION['arrayImg'] = $abc;
// To get the data on ajax hooked function -
// 获取 ajax 挂钩函数的数据 -
function resolve_the_ajax_request(){
if( !session_id())
session_start();
$abc = $_SESSION['arrayImg'];
}
回答by Talha
In my case I was using that session variable in plugin activation as well. So did something unorthodox. Instead of defining my session_start in a hook I made it as the first line in my plugin :).
就我而言,我也在插件激活中使用了该会话变量。所以做了一些非正统的事情。我没有在钩子中定义我的 session_start,而是将它作为插件中的第一行:)。
To heck with plugins, as soon as wordpress scans through my file it initiates the session.
看看插件,一旦 wordpress 扫描我的文件,它就会启动会话。
At the end I do not destroy the session on user logout. I simply unset my variable. This is to just in case if some other plugin is also using session. If I destroy session it may affect other plugins.
最后,我不会在用户注销时破坏会话。我只是取消设置我的变量。这是为了以防万一其他插件也在使用会话。如果我销毁会话,它可能会影响其他插件。
Cheers.
干杯。