如何在wordpress中不使用$_SESSION而使用会话

Dev*_*evD 4 php wordpress session

我正在尝试创建一个会话,而不使用 php$_SESSION变量,也不让用户登录网站。我创建了一个表单,一旦访问者/来宾用户提交表单,我想将他的数据存储在会话变量中。我发现$_SESSION在 WordPress 中使用并不是一个好的做法。我浏览了一些教程并发现可以使用WP_Session. 这似乎也不适合我。

这是我正在使用的代码:

global $wp_session;
$wp_session['visitorInfo'] = 'some_text_here';
Run Code Online (Sandbox Code Playgroud)

当我在另一个页面上请求它时,它什么也没有给我(空白)。即使我尝试打印$wp_session变量,它也会给我空白。我也尝试过$wp_session = WP_Session::get_instance();,但它返回给我错误Class WP_Session not found可能是因为我正在使用调用此方法的类的命名空间。

我也尝试过

add_action('init',array($this,'start_session'));
public function start_session(){
  if (!session_id()) { session_start();}
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

我的网站托管在 wpengine 上,它不允许创建自定义 cookie。我试图弄清楚当用户登录网站时 WordPress 如何创建会话。我过去两天一直在寻找解决方案,但没有找到任何有效的解决方案。

您能建议我如何实现这一目标吗?

非常非常感谢!

vee*_*vee 6

使用init钩子session_start()在没有 WP Engine 的普通服务器上工作正常。

示例代码:

<?php
/**
 * Plugin Name: Session plugin.
 */


add_action('init', 'sesp_init');
function sesp_init()
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    $_SESSION['hello'] = 'world';

    // maybe un-comment the line below if WordPress site health alert about active session.
    //session_write_close();
}


add_action('template_redirect', 'sesp_template');
function sesp_template()
{
    echo 'hello ' . $_SESSION['hello'].'<br>';
}
Run Code Online (Sandbox Code Playgroud)

它在首页上打招呼,世界。

但是,您可能需要session_write_close()在设置$_SESSION值后添加,因为 WordPress 站点运行状况可能会发出“检测到活动 PHP 会话”的警报。

WP_Session

该类WP_Session不是 WordPress 核心类。我在 WordPress 核心文件中找不到这个类,WP_Session_Token但它不用于会话使用。

该类WP_Session来自WP Session Manager 插件(参考这个问题)。您必须安装该插件才能访问WP_Session. 否则就会出现这个错误。

未找到 WP_Session 类

使用瞬态

From the document.

WordPress Transients API, which offers a simple and standardized way of storing cached data in the database temporarily

So, you can use it as alternative if session_start() is not really work and you don't want to install other plugin.

Example code:

add_action('init', 'sesp_init');
function sesp_init()
{
    set_transient('sesp_hello', 'moon', 60*5);// 5 minutes.
}


add_action('template_redirect', 'sesp_template');
function sesp_template()
{
    echo 'hello ' . get_transient('sesp_hello') . ' (use transient).<br>';
}
Run Code Online (Sandbox Code Playgroud)

You don't need to hook into init to set transient. The code above is for example. The third argument in set_transient() is expiration in seconds.

Transient Warning!

However, the transient is not for one visitor like the session. You have to set and check properly that the transient you are getting and setting is match for a person.

WP Engine

From their support page.

The biggest problem this presents is due to the unique session IDs. Unique IDs effectively bust cache and causes every session to become uncached. This will cause serious performance issues for your site.

You may switch to use PHP cookie or disable WP Engine cache. This was answered here.